How to call a data.frame inside an R Function by name

311 views Asked by At

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.

1

There are 1 answers

0
Roman Luštrik On BEST ANSWER

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