jesusgarciab - 1 month ago 6

R Question

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`

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