简体   繁体   English

如何通过名称调用R函数中的data.frame

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

I want to write a function that runs the same analysis on different data.frames. 我想编写一个在不同的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? 如何在函数内通过名称调用data.frame? Right now "data" obviously only returns the the names of "mydata" as a character. 现在,“ data”显然仅返回“ mydata”的名称作为字符。

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. 或者您可以将data.frames整理到一个列表中并进行处理。

mylist <- list(set1, set2)

lapply(mylist, FUN = function(yourdata) {
  print(summary(lm(x ~ y, data = yourdata)))
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM