将已定义的功能一次应用于所有数据框 [英] Apply an already defined function to all dataframes at once
问题描述
我已经定义了一个函数(可以正常工作).不过,我想在工作空间中将20个数据帧lapply
应用于相同的功能(dat1至dat20).
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)
但是,有没有一种方法可以用更短的命令来做到这一点,即将lapply
函数一次应用于所有数据帧呢?
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)
推荐答案
可以使用eval而不是lapply获得所需的行为.
The desired behavior can be obtained using eval instead of lapply.
假定mylist
是要应用fun
的data.frame的名称. mylist
可能是使用
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)
这篇关于将已定义的功能一次应用于所有数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!