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

查看:80
本文介绍了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变量跨越许多列

EDIT

Suppose, you have many observations per row i.e. x and y variables span over many columns

 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天全站免登陆