Apply an already defined function to all dataframes at once

让人想犯罪 __ 提交于 2019-12-06 11:53:21

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.

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

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