R 使用另一列中的数据添加数据列

R 使用另一列中的数据添加数据列,r,R,我试图从线性回归模型中绘制预测值。如何将使用我的一个数据列作为因子的预测值插入到数据帧中?我的数据框如下所示: score age rank 1 3.03 65 1 2 4.31 47 1 3 5.09 49 1 4 3.71 41 1 5 5.29 40 1 6 2.70 61 1 coefs = c(.085,

我试图从线性回归模型中绘制预测值。如何将使用我的一个数据列作为因子的预测值插入到数据帧中?我的数据框如下所示:

     score age rank 
  1  3.03  65    1         
  2  4.31  47    1       
  3  5.09  49    1       
  4  3.71  41    1        
  5  5.29  40    1         
  6  2.70  61    1   
coefs = c(.085, .018, .015)
intercepts = c(8.2, 4.2, 5.42)
d$predicted = intercepts[d$rank] + coefs[d$rank] * d$age
我已经根据我的lm预测了每个等级的分数(有3个),我想把它们插入数据框中,这样我就可以根据年龄绘制预测分数。预测得分为:

Rank 1 predicted tolerance score: (8.2+0)+(-.085+0)= 8.2 - .085 age
Rank 2 predicted tolerance score: (8.2-4.0)+(-.085+.103)=4.2 +.018 age
Rank 3 predicted tolerance score: (8.2-2.78)+(-.085+.07)=5.42 - .015 age
  Thank you!

你可以这样做:

     score age rank 
  1  3.03  65    1         
  2  4.31  47    1       
  3  5.09  49    1       
  4  3.71  41    1        
  5  5.29  40    1         
  6  2.70  61    1   
coefs = c(.085, .018, .015)
intercepts = c(8.2, 4.2, 5.42)
d$predicted = intercepts[d$rank] + coefs[d$rank] * d$age
(假设您的数据帧名为
d
)。

另一种方法:

parms <- data.frame(rank=1:3,int=c(8.2,4.2,5.42),slope=c(-0.85,0.017,-0.015))
mydata <- merge(mydata,parms)
mydata <- transform(mydata,predval=int+age*slope)
parms