user1833094
user1833094

Reputation: 1

add data column using data from another column

I am trying to plot predicted values from a linear regression model. How do I insert the prediction values, which use one of my data columns as a factor, into the dataframe? My data frame looks like this:

     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   

I have predicted scores for each rank (there are 3) based on my lm, and I want to insert these into the data frame so I can plot the predicted scores against age. The predicted scores are:

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!

Upvotes: 0

Views: 114

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226801

Another way to do it:

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)

If you have one set of data (i.e. these coefficients are based on the same data for which you want to predict)

lmfit <- lm(score~age*rank,data=mydata)
mydata$pred <- predict(lmfit)

Upvotes: 0

David Robinson
David Robinson

Reputation: 78630

You could do it like this:

coefs = c(.085, .018, .015)
intercepts = c(8.2, 4.2, 5.42)
d$predicted = intercepts[d$rank] + coefs[d$rank] * d$age

(assuming your data frame is called d).

Upvotes: 1

Related Questions