R 中变量名的向量 [英] vector of variable names in R

查看:34
本文介绍了R 中变量名的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自动生成单变量和多变量回归分析的函数,但我不知道如何在向量中指定 ** 变量...**这看起来很容易,但略读到目前为止我还没有弄清楚的文档......

I'd like to create a function that automatically generates uni and multivariate regression analyses, but I'm not able to figure out how I can specify **variables in vectors...**This seems very easy, but skimming the documentation I havent figured it out so far...

简单的例子

a<-rnorm(100)
b<-rnorm(100)
k<-c("a","b")
d<-c(a,b)
summary(k[1])

但是 k[1]="a" 是一个字符向量...d 只是 b 附加到 a,而不是变量名称.实际上,我希望 k[1] 表示向量 a.

But k[1]="a" and is a character vector...d is just b appended to a, not the variable names. In effect I'd like k[1] to represent the vector a.

感谢任何答案...

//M

推荐答案

可以使用get"函数根据对象名称的字符串来获取对象,但从长远来看最好是存储变量在列表中并以这种方式访问​​它们,事情变得简单得多,您可以获取子集,您可以使用 lapply 或 sapply 在每个元素上运行相同的代码.保存或删除时,您可以只处理整个列表,而不是试图记住每个元素.例如:

You can use the "get" function to get an object based on a character string of its name, but in the long run it is better to store the variables in a list and just access them that way, things become much simpler, you can grab subsets, you can use lapply or sapply to run the same code on every element. When saving or deleting you can just work on the entire list rather than trying to remember every element. e.g.:

mylist <- list(a=rnorm(100), b=rnorm(100) )
names(mylist)
summary(mylist[[1]])
# or
summary(mylist[['a']])
# or
summary(mylist$a)
# or 
d <- 'a'
summary(mylist[[d]])

# or
lapply( mylist, summary )

如果您使用 lm(或其他建模函数)以编程方式创建用于分析的模型,那么一种方法是仅对数据进行子集化并使用.",例如:

If you are programatically creating models for analysis with lm (or other modeling functions), then one approach is to just subset your data and use the ".", e.g.:

yvar <- 'Sepal.Width'
xvars <- c('Petal.Width','Sepal.Length')
fit <- lm( Sepal.Width ~ ., data=iris[, c(yvar,xvars)] )

或者您可以使用paste"或sprintf"构建公式,然后使用as.formula"将其转换为公式,例如:

Or you can build the formula using "paste" or "sprintf" then use "as.formula" to convert it to a formula, e.g.:

yvar <- 'Sepal.Width'
xvars <- c('Petal.Width','Sepal.Length')
my.formula <- paste( yvar, '~', paste( xvars, collapse=' + ' ) )
my.formula <- as.formula(my.formula)
fit <- lm( my.formula, data=iris )

如果您正在查看自动拟合的许多不同模型,请注意多重比较的问题.

Note also the problem of multiple comparisons if you are looking at many different models fit automatically.

这篇关于R 中变量名的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆