将lm应用于由第三列定义的数据帧子集 [英] Apply lm to subset of data frame defined by a third column of the frame
本文介绍了将lm应用于由第三列定义的数据帧子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,其中包含一个x值的向量,一个y值的向量和一个ID的向量:
x< - rep(0:3,3)
pre>
y< - runif(12)
ID< - c(rep(a,4),rep(b ,4),rep(c,4))
df< - data.frame(ID = ID,x = x,y = y)
我想为x和y共享相同ID的子集创建一个单独的lm。以下代码完成工作:
a.lm < - lm(x〜y,data = subset(df, ID =a))
b.lm < - lm(x〜y,data = subset(df,ID ==b))
c.lm< - lm x〜y,data = subset(df,ID ==c))
非常脆弱(未来数据集可能有不同的ID)和未向量化。我也想把所有的lms存储在一个单一的数据结构中。必须有一个优雅的方式来做到这一点,但我找不到。任何帮助?
解决方案如何
library(nlme)## OR library(lme4)
lmList(x〜y | ID,data = d)
?
I've got a data frame containing a vector of x values, a vector of y values, and a vector of IDs:
x <- rep(0:3, 3) y <- runif(12) ID <- c(rep("a", 4), rep("b", 4), rep("c", 4)) df <- data.frame(ID=ID, x=x, y=y)
I'd like to create a separate lm for the subset of x's and y's sharing the same ID. The following code gets the job done:
a.lm <- lm(x~y, data=subset(df, ID=="a")) b.lm <- lm(x~y, data=subset(df, ID=="b")) c.lm <- lm(x~y, data=subset(df, ID=="c"))
Except that this is very brittle (future data sets might have different IDs) and un-vectorized. I'd also like to store all the lms in a single data structure. There must be an elegant way to do this, but I can't find it. Any help?
解决方案How about
library(nlme) ## OR library(lme4) lmList(x~y|ID,data=d)
?
这篇关于将lm应用于由第三列定义的数据帧子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文