简体   繁体   中英

how to pass a variable to lm within a function in R

Here is a (non)working example of how I would like to do things. The restriction is that all this has to happen within a function and that K should not be appended to x . What's the right way to do this? The issue is that K is not associated with the correct environment here.

EDIT: based on the comments below. the answer provided works but we still don't yet understand why

f = function() { K=5; x = data.frame(a=1:10, b=(1:10)^2); 
                 regstr = "b ~ a:I(a>K)";
                 lm(regstr, data=x);
                }
f()
Error in unique(c("AsIs", oldClass(x))) (from #3) : object 'K' not found 



> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=C                 LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
 [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
 [1] stats     graphics  grDevices utils     datasets  methods   base  
f = function() { K=5; x = data.frame(a=1:10, b=(1:10)^2); 
                  regstr = "b ~ a:I(a>K)";
                  lm(as.formula(regstr), data=x);
}

you missed the

as.formula

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM