subset multiple data tables using lapply

给你一囗甜甜゛ 提交于 2019-12-11 04:17:49

问题


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 ?


回答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)



回答2:


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)


来源:https://stackoverflow.com/questions/30359317/subset-multiple-data-tables-using-lapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!