jesusgarciab jesusgarciab - 1 month ago 6
R Question

Changing colnames of the nth element of a list of data.frames

I have a list of data frames names

I used objects() to get them.

my_list <- objects()

my_list

[1]"df1"
[2]"df2"
[3]"df3"
[4]"df4"
...


Each data frame has 7 columns

I have 3 different character vectors
v1,v2,v3
(length 4) that I want to use to name the first 4 columns of the data frames. I basically want to reuse those vectors in that order until all the columns in my data.frame list are named.

df1

X1 X2 X3 X4 X5 X6 X7
1 NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA

v1 <- c(a,b,c,d)


magic(my_list)

df1

a b c d X5 X6 X7
1 NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA
...

Answer

Setnames from the data.table package will work.

setnames(df,old = c(1:4), new = v1[1:4])

edit: If you want to do that for your entire list, you can use lapply.

lapply(l, function(x) setnames(x,old = c(1:4), new = v1[1:4]))