[R] using a variable for a column name in a formula

arun smartpink111 at yahoo.com
Mon Oct 14 00:13:03 CEST 2013


Hi,
I am getting this:

#Using an example dataset:
set.seed(24)
 X <- data.frame(weight=sample(100:250,20,replace=TRUE),height=sample(140:190,20,replace=TRUE))

nnn <- "height"

res <- lm(as.formula(paste(nnn, "~.")),data=X)
 res2 <- lm(get(nnn) ~ . ,data=X)
 coef(res)
 (Intercept)       weight 
169.24873241  -0.03881928 


coef(res2)
  (Intercept)        weight        height 
-7.890309e-14  1.518345e-17  1.000000e+00 
A.K.


On Sunday, October 13, 2013 6:06 PM, p_connolly <p_connolly at slingshot.co.nz> wrote:
On 2013-10-14 10:04, David Epstein wrote:
> lm(height ~ ., data=X)
> works fine.
> 
> However
> nnn <- "height" ;  lm(nnn ~ . ,data=X)
> fails
> 
> How do I write such a formula, which depends on the value of a string
> variable like nnn above?

as.formula() with paste() could work, but from where you are now, try
lm(get(nnn) ~ . ,data=X)


HTH

> 
> A typical application might be a program that takes a data frame
> containing only numerical data, and figures out which of the columns
> can be best predicted from all the other columns.
> 
> Thanks
> David
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list