[R] how to merge the fitted values from a linear model?

Chuck Cleland ccleland at optonline.net
Wed Sep 2 02:13:42 CEST 2009


On 9/1/2009 6:32 PM, kayj wrote:
> Hi All,
> 
> I would like to run a linear model where the response is the duration of
> relief in days and the regressor is the drug dosage in mg. Then I would like
> compute the predicted values of the duration of relief from the model and
> merge it into the original data. I am not sure how the merge happens since
> if I have missing values in the data, R runs the resgression model but
> fitted values for some observations are not being calculated.
> 
> Below is my R script
> 
> Mydata<-read.csv(file=”file1.csv”, header=T)
> 
> Model<-lm(y ~ x, data=Mydata)
> f<-fitted(Model)
> Newdata<-cbind(f , Mydata)
> 
> Is Newdata merged correctly?
> 
> Thanks for your help

  You might try something like this:

DF <- data.frame(Y = rnorm(20), X = sample(c(NA,0,1,2,3), size=20,
replace=TRUE))

DF$f <- fitted(lm(Y ~ X, data=DF, na.action=na.exclude))

DF
             Y  X          f
1   0.81371693  2  0.1116813
2  -0.36585221  0 -0.8160565
3  -1.07271855  0 -0.8160565
4   1.27182331  1 -0.3521876
5  -0.12492961  2  0.1116813
6  -1.84241736  0 -0.8160565
7  -0.28532869  1 -0.3521876
8   1.17361614 NA         NA
9   0.88190221  3  0.5755502
10  0.92742858  1 -0.3521876
11 -1.18675102  0 -0.8160565
12  0.38076816 NA         NA
13 -1.31518961  0 -0.8160565
14 -1.07973072  1 -0.3521876
15  0.00431749  3  0.5755502
16  0.49820163  3  0.5755502
17 -0.21377954  1 -0.3521876
18 -1.03107537  2  0.1116813
19 -1.23459162  0 -0.8160565
20 -0.05666561  0 -0.8160565

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list