0

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.

IMPORTANT: I want to use the 3 vectors to name all the data frames. v1 to name df1, v2 to name df2, v3 to name df3, v1 AGAIN to name df4, etc...

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
 ...
jesusgarciab
  • 129
  • 11

1 Answers1

1

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]))

edit2:Recycling the 3 vectors, and keeping it a bit easy to read -

 for (i in 1:length(l))
          {
  if (i%%3 == 1) {
    setnames(l[[i]],old = c(1:4), new = v1[1:4])
  }
  else if (i%%3 == 2) {
    setnames(l[[i]],old = c(1:4), new = v2[1:4])
  }
  if (i%%3 == 0) {
    setnames(l[[i]],old = c(1:4), new = v3[1:4])
  }
}
Adit Sanghvi
  • 142
  • 1
  • 2
  • 12