R - 在每个数据框行上应用 lm [英] R - apply lm on each data frame row

查看:29
本文介绍了R - 在每个数据框行上应用 lm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数据框的两列之间对每一行应用简单的线性回归.经过一番研究,我觉得我快到了,但我的功能仍然不起作用.请看:

I am trying to apply a simple linear regression between two columns of a data frame, for every row. After some research I feel like I am almost there, but my function still doesn't work. Please take a look:

set.seed(1)
DF <- data.frame(A=rnorm(50, 100, 3),
                 B=rnorm(50, 100, 3))

resultlist   <- apply(DF, 1, function(y) lm(y ~ x))
resultcoeffs <- apply(DF, 1, function(y) lm(y ~ x)$coefficients)

有关如何实现这一目标的任何提示?

Any tip on how to achieve that?

提前致谢.

推荐答案

每行只有一个观察.请注意,您会得到 NA 估计值,因为没有足够的自由度.

It is just one observation per row. Note that you get NA estimates as there are not enough degrees of freedom.

这个想法是:

 mapply(function(x,y) lm(y~x)$coefficients, DF[,1], DF[,2])

 apply(DF1, 1, function(x) lm(x[2]~x[1])$coefficients)

编辑

假设您每行有许多观察值,即 xy 变量跨越多列

 mapply(function(x,y) lm(y~x)$coefficients, as.data.frame(t(DFNew[1:3])),
                             as.data.frame(t(DFNew[4:6])))

 apply(DFNew, 1, function(x) lm(x[4:6]~x[1:3])$coefficients)

数据

set.seed(25)
DFNew <- as.data.frame(matrix(sample(1:50,10*6, replace=TRUE), ncol=6))

这篇关于R - 在每个数据框行上应用 lm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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