2

I have multiple data tables and all have a common column called ID. I have a vector vec that contains a set of ID values. I would like to use lapply to subset all data tables using vec I understand how to use lapply to subset the data tables but my question is how to assign the subsetted results back to original data tables Here is what I tried :

 tables<-c("dt1","dt2","dt3","dt4")
 lapply(mget(tables),function(x)x[ID %in% vec,])

The above gives subsets of all data tables but how do I assign them back to dt1,dt2,dt3,dt4 ?

Sri
  • 1,130
  • 1
  • 15
  • 31
  • 2
    I think the `ID` should be `x$ID` if you didn't attach the dataset (attach is not reccommended). Also, it is better to keep it in the list rather than having many objects in the global environment. You can use `list2env` if you insist. it. `lst <- lapply(mget(tables),function(x)x[ID %in% vec,]); list2env(lst, envir=.GlobalEnv)` – akrun May 20 '15 at 20:07
  • Thanks akrun, I have never used list2env but seems to be working. One question : I'm using this in an R shiny application. Converting the list to objects in Global Environment - would it interfere with other user sessions? – Sri May 20 '15 at 20:22
  • I didn't understand `other user sessions`. It is generally not good to have a lot of objects in the global environment – akrun May 20 '15 at 20:26

2 Answers2

1

I would keep the datasets in the list rather than updating the dataset objects in the global environment as most of the operations can be done within the list (including reading the files and writing to output files ). But, if you insist, we can use list2env which will update the original dataset objects with the subset dataset

 lst <- lapply(mget(tables),function(x)x[ID %in% vec,])
 list2env(lst, envir=.GlobalEnv)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You could also just name the datasets in the list:

tables <- c("dt1","dt2","dt3","dt4")
dflist <- lapply(mget(tables),function(x)x[ID %in% vec,])
dflist <- setNames(dflist, tables)
SCDCE
  • 1,603
  • 1
  • 15
  • 28