在R中使用lm()作为公式的快捷方式 [英] Shortcut using lm() in R for formula
本文介绍了在R中使用lm()作为公式的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在lm()
m <- matrix(rnorm(100), ncol=5)
lm(m[,1] ~ m[,2:5]
此处与
lm(m[,1] ~ m[,2] + m[,3] + m[,4] + m[,5]
但是在变量不处于同一级别的情况下(至少这是我目前的假设),此操作不起作用,并且出现错误:
but in the case when variables are not of the same level (at least this is my assumption for now) this does not work and I get the error:
Error in model.frame.default(formula = hm[, 1] ~ hm[, 2:4], drop.unused.levels = TRUE) :
invalid type (list) for variable 'hm[, 2:4]'
数据(hm):
N cor.distance switches time
1 50 0.04707842 2 0.003
2 100 -0.10769441 2 0.004
3 200 -0.01278359 2 0.004
4 300 0.04229509 5 0.008
5 500 -0.04490092 6 0.010
6 1000 0.01939561 4 0.007
还有一些捷径可以避免写长公式吗?
Is there some shortcut still possible to avoid having to write the long formula?
推荐答案
尝试lm(y ~ ., data)
,其中.
表示"data
中除y
之外的所有其他列.
Try lm(y ~ ., data)
where .
means "every other column in data
besides y
.
m <- matrix(rnorm(100), ncol =5)
m <- as.data.frame(m)
names(m) <- paste("m", 1:5, sep="")
lm(m1 ~., data=m)
您可以重新分配m
以仅包括您作为预测变量的列
You can reassign m
to include only the columns you as the predictors
m <- m[ ,2:4]
lm(m1 ~ ., data=m)
这篇关于在R中使用lm()作为公式的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文