[R] how to get "lsmeans"?

Liaw, Andy andy_liaw at merck.com
Wed Mar 21 13:28:28 CET 2007


I verified the result from the following with output from JMP 6 on the
same data (don't have SAS: don't need it):

set.seed(631)
n <- 100
dat <- data.frame(y=rnorm(n), A=factor(sample(1:2, n, replace=TRUE)),
                  B=factor(sample(1:2, n, replace=TRUE)),
                  C=factor(sample(1:2, n, replace=TRUE)),
                  d=rnorm(n))
fm <- lm(y ~ A + B + C + d, dat)
## Form a data frame of points to predict: all combinations of the
## three factors and the mean of the covariate.
p <- data.frame(expand.grid(A=1:2, B=1:2, C=1:2))
p[] <- lapply(p, factor)
p <- cbind(p, d=mean(dat$d))
p <- cbind(yhat=predict(fm, p), p)
## lsmeans for the three factors:
with(p, tapply(yhat, A, mean))
with(p, tapply(yhat, B, mean))
with(p, tapply(yhat, C, mean))

Andy 

From: Xingwang Ye
> 
> Dear all, 
>       
>     I search the mail list about this topic and learn that no 
> simple way is available to get "lsmeans" in R as in SAS.
>     Dr.John Fox and Dr.Frank E Harrell have given very useful 
> information about "lsmeans" topic.    
>     Dr. Frank E Harrell suggests not to think about lsmeans, 
> just to think about what predicted values wanted
>     and to use the predict function. However, after reading 
> the R help file for a whole day, I am still unclear how to do it.
>     Could some one give me a hand? 
>  
> for example:
>   
> A,B and C are binomial variables(factors); d is a continuous 
> variable ; The response variable Y is  a continuous variable too.  
> 
> To get lsmeans of Y according to A,B and C, respectively, in 
> SAS, I tried proc glm data=a;  class A B C;  model Y=A B C d; 
>  lsmeans A B C/cl; run;  
> 
> In R, I tried this:  
>  library(Design)
>  ddist<-datadist(a)
>  options(datadist="ddist")
>  f<-ols(Y~A+B+C+D,data=a,x=TRUE,y=TRUE,se.fit=TRUE)  
> 
> then how to get the "lsmeans" for A, B, and C, respectively 
> with predict function?
> 
>  
> 
> Best wishes
> yours, sincerely 
> Xingwang Ye    
> PhD candidate     
> Research Group of Nutrition Related Cancers and Other Chronic 
> Diseases      
> Institute for Nutritional Sciences,  
> Shanghai Institutes of Biological Sciences,     
> Chinese Academy of Sciences     
> P.O.Box 32     
> 294 Taiyuan Road     
> Shanghai 200031     
> P.R.CHINA
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}



More information about the R-help mailing list