[R] Using a variable in the formula

Rolf Turner r.turner at auckland.ac.nz
Tue Oct 27 05:24:48 CET 2009


On 27/10/2009, at 4:26 PM, jmark17 wrote:

>
> I am sure this question has come up, but searching hasn't given me any
> results.
>
> So I need to enter this line:
>
> mx1 <- randomForest(X1 ~ elevation + slope + vegtype, data =  
> moths.train)
>
> But the problem is that X1 is currently hard coded. I would instead  
> like to
> be able to put in the value of X1 through a list. For example:
>
> list <- list("X1", "X2", "X3")
> #Then, instead of X1, I want to put list[1]

	No you don't.  You *might* want to put list[[1]] --- learn
	the difference between [[]] and [] for lists, i.e. RTFM, in
	particular ?"[" --- but it still wouldn't work.

> mx1 <- randomForest(list[1] ~ elevation + slope + vegtype, data =
> moths.train)
>
> randomForest does not accept list[1] as a valid entry, so how can I  
> get it
> to accept it as X1, instead of list[1]?

(a) Don't call your list ``list''.  (Cf. fortune("dog").)

(b) You really want a character *vector* not a list.  E.g.

	nms <- c("X1", "X2", "X3")

(c) Execute

	fmla <- as.formula(paste(nms[1],"~ elevation + slope + vegtype"))
	mxl  <- randomForest(fmla,data=moths.train)

Have tested the construction of ``fmla'' --- that works.  I don't know
from randomForest(), so I haven't tested that bit.

HTH.

	cheers,

		Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}




More information about the R-help mailing list