data.table's set in a loop

Say I have 2 df


df <- data.table(x = letters[1:2])
df_1 <- data.table(x = letters[3:4])

and I wanted to use set to create a new column in both df (but using an existing column as input)

names_df <- c('df', 'df_1')
for(i in names_df)
  set(get(i), j = 'y', value = toupper(.$x))

The above would give me error:

Error in toupper(.$x) : object '.' not found

I have resorted to this post and used .$ but of course, to no avail. Any help would be much appreciated.

>Solution :

You may want to use get

for(i in names_df){
  set(get(i), j = 'y', value = toupper(get(i)$x))

> df
   x y
1: a A
2: b B
> df_1
   x y
1: c C
2: d D

If you want .$x to work, you need to use the pipe operator:

for(i in names_df){
  get(i) %>% 
    set(., j = 'y', value = toupper(.$x))

Leave a Reply