I want to write a function that runs the same analysis on different data.frames. Here is a simple version of my code:
set1 <- data.frame(x=c(1,2,4,6,2), y=c(4,6,3,56,4))
set2 <- data.frame(x=c(3,2,3,8,2), y=c(2,6,3,6,3))
mydata <- c("set1", "set2")
for (dataCount in 1:length(data)) {
lm(x~y, data=mydata)
}
How do I call a data.frame by name inside the function? Right now "data" obviously only returns the the names of "mydata" as a character.
There are number of ways of doing this. Your "native" way would be
mydata <- ls(pattern = "set")
for (dataCount in mydata) {
print(summary(lm(x~y, data=get(dataCount))))
}
or you could collate your data.frames into a list and work on that.
mylist <- list(set1, set2)
lapply(mylist, FUN = function(yourdata) {
print(summary(lm(x ~ y, data = yourdata)))
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.