Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting coefficient names to a formula in R
    text
    copied!<p>When using formulas that have factors, the fitted models name the coefficients XY, where X is the name of the factor and Y is a particular level of it. I want to be able to create a formula from the names of these coefficients.</p> <p>The reason: If I fit a lasso to a sparse design matrix (as I do below) I would like to create a new formula object that only contains terms for the nonzero coefficients.</p> <pre><code>require("MatrixModels") require("glmnet") set.seed(1) n &lt;- 200 Z &lt;- data.frame(letter=factor(sample(letters,n,replace=T),letters), x=sample(1:20,200,replace=T)) f &lt;- ~ letter + x:letter + I(x&gt;5):letter X &lt;- sparse.model.matrix(f, Z) beta &lt;- matrix(rnorm(dim(X)[2],0,5),dim(X)[2],1) y &lt;- X %*% beta + rnorm(n) myfit &lt;- glmnet(X,as.vector(y),lambda=.05) fnew &lt;- rownames(myfit$beta)[which(myfit$beta != 0)] [1] "letterb" "letterc" "lettere" [4] "letterf" "letterg" "letterh" [7] "letterj" "letterm" "lettern" [10] "lettero" "letterp" "letterr" [13] "letters" "lettert" "letteru" [16] "letterw" "lettery" "letterz" [19] "lettera:x" "letterb:x" "letterc:x" [22] "letterd:x" "lettere:x" "letterf:x" [25] "letterg:x" "letterh:x" "letteri:x" [28] "letterj:x" "letterk:x" "letterl:x" [31] "letterm:x" "lettern:x" "lettero:x" [34] "letterp:x" "letterq:x" "letterr:x" [37] "letters:x" "lettert:x" "letteru:x" [40] "letterv:x" "letterw:x" "letterx:x" [43] "lettery:x" "letterz:x" "letterb:I(x &gt; 5)TRUE" [46] "letterc:I(x &gt; 5)TRUE" "letterd:I(x &gt; 5)TRUE" "lettere:I(x &gt; 5)TRUE" [49] "letteri:I(x &gt; 5)TRUE" "letterj:I(x &gt; 5)TRUE" "letterl:I(x &gt; 5)TRUE" [52] "letterm:I(x &gt; 5)TRUE" "letterp:I(x &gt; 5)TRUE" "letterq:I(x &gt; 5)TRUE" [55] "letterr:I(x &gt; 5)TRUE" "letteru:I(x &gt; 5)TRUE" "letterv:I(x &gt; 5)TRUE" [58] "letterx:I(x &gt; 5)TRUE" "lettery:I(x &gt; 5)TRUE" "letterz:I(x &gt; 5)TRUE" </code></pre> <p>From this I would like to have a formula</p> <pre><code>~ I(letter=="d") + I(letter=="e") + ...(etc) </code></pre> <p>I checked out formula() and all.vars() to no avail. Also, writing a function to parse this is a bit of a pain because of the different types of terms that can arise. For example, for x:letter when x is a numeric value and letter is a factor, or I(x>5):letter as another annoying case.</p> <p>So am I not aware of some function to convert between formula and its character representation and back again?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload