Savi Savi - 23 days ago 11
R Question

Rename columns in a dataframe the same name as list elements in R - Solved

I have a large list of file names ["fname1","fname2",..."fname50"].

I would like to change the column names the dataframe I'm working with to match the file names. For example, column1's name should change to fname1, column2's name to fname2, and so on. Actual column names are results of cbind and are pretty long/messy so it's not just one-word replacements or anything.

I can do this as a one-off

>names(df)[1]<-filenames[1]


However, I am having trouble making this work in a loop.

>for(i in df){names(df)[i]<-filenames[i]}
>error msg: 'names' attribute [39] must be the same length as the vector [5]


I usually work in Python and am probably treating loops incorrectly in R. I would appreciate tips and tricks. Thank you!

In pseudo-Python, what I'm looking for is:

for i in df-colnames:
df-colnames[i] = filenames[i]


The solution:

names(df)<-filesnames


Thank you everyone that commented. This worked.

Answer

Regardless if it's a list or a vector, you can simply do

names(df) = filenames
Comments