[R] predict.lm within a function
Pamela McCaskie
pmccask at cyllene.uwa.edu.au
Thu Aug 31 14:33:41 CEST 2006
Hi
I'm trying to wrap predict.lm within a function, but I'm having problems
passing arguments into it in this way.
Basically I want to create a lm object, then pass it into the predict.lm
function and be able to tell predict.lm which variable I want to predict
for, by passing the variable name as an argument of the wrapper
function. This variable will always be a factor with 3 levels, so I want
to predict the response within each of these levels evaluated at the
mean value of all other variables in the model (as indicated below by
replicating the means for the data 3 times in the data.frame part of
predict.lm).
The simplest of all my attempts looks like this:
my.fun <- function(formula, mydata, predict_variable){
my.lm <- lm(formula=formula, data=mydata)
my.predict <-
predict.lm(my.lm,(data.frame(predict_variable=y,rbind(mean(mydata,
na.rm=T),mean(mydata, na.rm=T), mean(mydata,na.rm=T)),
row.names=as.numeric(names(table(mydata$predict_variable))))))
}
outside of the function, the following commands do exactly what I want:
my.lm <- lm(LDL ~ AGE + SEX + factor(SNP1_add), data=testdata)
predict.lm(my.lm,(data.frame(SNP1_add=y,rbind(mean(testdata,
na.rm=T),mean(testdata, na.rm=T), mean(testdata,na.rm=T)),
row.names=as.numeric(names(table(testdata$SNP1_add))))))
where SNP1_add is the variable to predict for, but when I run
my.fun(formula=LDL ~ AGE + SEX + factor(SNP1_add), mydata=testdata,
predict_variable="SNP1_add")
I get: Error in sort(unique.default(x), na.last = TRUE) :
'x' must be atomic
I figure I should be using eval() or substitute() somewhere to but none
of my attempts have been successful. Any help would be appreciated.
--
Pamela A McCaskie
BSc(Mathematical Sciences)(Hons)
Laboratory for Genetic Epidemiology
Western Australian Institute for Medical Research
University of Western Australia
Ground Floor, B Block
Hospital Avenue, Nedlands
Western Australia 6009
AUSTRALIA
Email: pmccask at cyllene.uwa.edu.au
Phone: +61 (0)8 9346 1612
Mob: +61 (0)417 926 607
This e-mail and all attachments contain information which is confidential and/or subject to copyright. It may not be used or disclosed unless authorised by the sender.
More information about the R-help
mailing list