Apply an already defined function to all dataframes at once

末鹿安然 提交于 2020-02-22 08:08:16

问题


I already have defined a function (which works fine). Nevertheless, I have 20 dataframes in the working space to which I want to lapply the same function (dat1 to dat20).

So far it looks like this:

dat1 <- func(dat=dat1)
dat2 <- func(dat=dat2)
dat3 <- func(dat=dat3) 
dat4 <- func(dat=dat4)
...
dat20 <- func(dat=dat20)

However, is there a way to do this more elegant with a shorter command, i.e. to lapply the function to all dataframes at once?

I tried this, but it didn't work:

mylist <- paste0("dat", 1:20, sep="")
lapply(mylist, func) 

回答1:


Try something like:

lapply(mget(ls(pattern="dat")),func)

Some details: The pattern argument in ls will limit which object names it lists (e.g., I assume you have other objects including your function in the global environment). mget retrieves those objects from the environment and turns them into a list, which you can then lapply your function over.




回答2:


If you have the name of a variable, you can use get() to retrieve the value from the workspace. The corresponding assignment function is called assign():

mylist <- paste0("dat", 1:20)
lapply(mylist, function(name) assign(name, func(dat=get(name))) )



回答3:


The desired behavior can be obtained using eval instead of lapply.

Assume mylist to be the names of the data.frame you want to apply fun to. mylist might be generated using

mylist <- ls(pattern="dat")

Then you can use the following code to do exactly what you want:

cCmd  <- paste(mylist , "<- func(" ,mylist,")", sep="")
eCmd  <- parse(text=cCmd)
eval(eCmd)


来源:https://stackoverflow.com/questions/18389767/apply-an-already-defined-function-to-all-dataframes-at-once

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