'Using vector and seq to rename dataframe

I have a .csv file with scanning spectroscopic data. Each run generates to types of data the wavelength and the absorption. the first line in the .csv looks like this Sample1,,220201_CBP21_WT,, giving me the name of the sample run as the name of the wavelength column when imported and nothing (ie the numbered position) for the absorbtion. I want to copy the name of the first column to the second and combine it with a string like "abs" for every other column.

tried to just give them same name with name and rename just as a starting point but couldn't get that to work either

df = data.frame(firstname = c(1,2,3),"1" = c(13,13,15), secondname = c(1,2,3), "2" = c(12,13,12))

oldnames = names(df)
names(df[seq(1,3,2)]) = oldnames[seq(2,4,2)]

#or
rename(df,df[seq(1,3,2)]) = oldnames[seq(2,4,2)])

So I want the names to df to be firstname, firstname, secondname, secondname at the very least idealy somthing like firstname, firstname_abs, secondname, secondname_abs



Solution 1:[1]

So, if I understand correctly, you have 2 columns and you want to rename your second column to something like (first column)_(second column)

But in any case as general solution what you're probably looking for is paste() or paste0() So it should be something like -

df$column = paste("text",df$column,sep = "separator")

OR

df$columnB = paste(df$columnA,df$columnB,sep = "separator")

paste() requires you set the separator or sets a space by default

You can use paste0() which doesn't have any separator requirement just joins as is

df$column = paste0("text","separator if required",df$column)

OR

df$columnB = paste(df$columnA,"separator if required",df$columnB)

Your question is slightly vague as to what sort of result you want exactly, maybe you can type out a sample of the input and output you expect. Then I can improve the answer.

Edit: Based on your comment you can do something like to rename every alternate columns the way you want -

Extract the column names:

temp_names = colnames(df)

Then change every alternate name in the list by pasting _abs to the one before it:

temp_names[c(seq(2,length(temp_names),2))] = paste0(temp_names[c(seq(1,length(temp_names),2)),"_abs"])

Then rename the columns:

colnames(df) = temp_names

Example Run:

temp_names = c("test1","","test2","","test3","")
temp_names
[1] "test1" ""      "test2" ""      "test3" ""
temp_names[c(seq(2,length(temp_names),2))] = paste0(temp_names[c(seq(1,length(temp_names),2))],"_abs")
temp_names
[1] "test1"     "test1_abs" "test2"     "test2_abs" "test3"     "test3_abs"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1