Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data.table's set in a loop

Say I have 2 df

library(data.table)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading