Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

r - Using lapply to apply a function over list of data frames and saving output to files with different names

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 list

something 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 named A and B) that correspond with the modified data frames.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will work with the following lapply call:

lapply(names(mylist), function(x) NewVar(mylist[[x]], "y", x))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...