使用lapply将功能应用于数据帧列表,并将输出保存到具有不同名称的文件 [英] Using lapply to apply a function over list of data frames and saving output to files with different names
问题描述
例如
df1 < - data.frame(x = c(1:5),y = c(11:15))
df2 < - data.frame(x = c(1:5),y = c(11:15))
mylist < - list(A = df1,B = df2)
我有一个我要应用于每个数据框架的功能;在这个函数中,我想包括一行将结果写入文件(最终我想做更复杂的事情,例如保存每个数据框架的两个变量之间的相关关系图,但是以为我会开始简单)
例如
NewVar< - function(mydata,whichVar,i){
mydata $ newVar< - mydata [,whichVar] + 1
write.csv(mydata,file = i)
}
我想使用 lapply()
将此函数应用于列表中的每个数据框
如下:
hh< -lapply(mylist,NewVar,whichVar =y )
我无法弄清楚如何在lapply的上下文中分配i i
遍历数据框列表中的名称,保存不同名称的多个文件(在这种情况下,两个文件名为 A
和 B
)与修改后的数据帧相对应。
它将适用于以下 lapply
call:
lapply(names(mylist),function(x)NewVar(mylist [[x]],y,x))
/ pre>
I have a list of data frames and have given each element in the list (e.g. each data frame) a name:
e.g.
df1 <- data.frame(x = c(1:5), y = c(11:15)) df2 <- data.frame(x = c(1:5), y = c(11:15)) mylist <- list(A = df1, B = df2)
I have a function that I want to apply to each data frame; In this function, I want to include a line to write the results to file (eventually I want to do more complicated things like save plots of the correlation between two variables for each data frame but thought I'd start simple)
e.g.
NewVar <- function(mydata, whichVar, i) { mydata$newVar <- mydata[, whichVar] + 1 write.csv(mydata, file = i) }
I want to use
lapply()
to apply this function to each data frame in my listsomething like:
hh<-lapply(mylist, NewVar, whichVar = "y")
I can't figure out how to assign the "i" within the context of lapply so that
i
iterates over the names in the list of data frames, saving multiple files with different names (in this case, two files namedA
andB
) that correspond with the modified data frames.解决方案It will work with the following
lapply
call:lapply(names(mylist), function(x) NewVar(mylist[[x]], "y", x))
这篇关于使用lapply将功能应用于数据帧列表,并将输出保存到具有不同名称的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!