Skip to content
Prev 302720 / 398502 Next

Pass Conditional & loop argument into a function

First thing; are you trying to fit a model specified as

y ~ X + X^2 + X^3 ?

... because if you are you're unlikely to get anything useful. That uses formula syntax in which ^ does not have the arithmetic power meaning; see section 11.1 'Defining statistical models; formulae' in 'an introduction to R' in your HTML help system. This formula only specifies one term, X, so all you'll get is the result of

y ~ X

If you wanted to fit a polynomial the hard (and not generally good) way you'd have to do 

y ~ I(X )+ I(X^2) + I(X^3) 

Next, in your line
 fit <- lm(Y~conditional.argument)

you have asked lm to fit Y to a character string formed by paste(). That is also unlikely to be useful. You would need to create the complete formula as a string (eg "Y~X+I(X^2)+I(X^3)" ) and then use as.formula to convert that to a formula lm can use.

Then there's the unnecessary loop. You can get your formula string without a loop from an integer 'degree' using 

formstring <- paste("Y ~ ", paste("I(X^",1:degree,")" , sep="", collapse=" + "))

And then you can convert formstring to a formula object and use the formula object in lm:
form <- as.formula(formstring) #be careful with this; it looks for the terms in the current environment... 
lm(form)


Or, if 'degree' were a vector (say 
degree<-c(1, 3, 5)
formstring <- paste("Y ~ ", paste("I(X^",degree,")" , sep="", collapse=" + "))
and so on.
I don't know what you're trying to achieve with boxplot, but if you gave boxplot itself your vectors it would plot them by itself:

x<-rnorm(17)
y<-runif(23)
z<-c(x,y)

boxplot(x,y,z)

Incidentally, this:
conditional.argument <- data[,1], data[,2], ...,data[,nvariables]          #
is not a valid assignment in R, so it cannot be the code you used. And using something called 'data' (or any other object) in a function that does not have an named argument by the same name is asking for trouble; there is no telling where it will get 'data' from but there is a very good chance it will sometimes be from somewhere you don't expect. 


S Ellison
*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}