Note that there are some explanatory texts on larger screens.

plurals
  1. POCoefficient Variable Membership in R
    primarykey
    data
    text
    <p>I have worked up a horribly lengthy solution to this before using regular expressions but I hope there is a more native way to do it.</p> <p>Given a model, perhaps like</p> <pre><code>data(tips, package="reshape2") mod &lt;- lm(tip ~ total_bill*sex + sex*day, tips) mod$coefficients </code></pre> <p>I want to identify which coefficients go with which variable in the formula. Like this:</p> <pre><code>| Coefficient | Variable | |:-------------------|:---------------| | total_bill | total_bill | | sexMale | sex | | daySat | day | | daySun | day | | dayThur | day | | total_bill:sexMale | total_bill,sex | | sexMale:daySat | sex,day | | sexMale:daySun | sex,day | | sexMale:dayThur | sex,day | </code></pre> <p>I have inspected <code>model.matrix</code> and <code>model.formula</code> but those led me to this line of code</p> <pre><code>.Internal(model.matrix(t, data)) </code></pre> <p>I dove into the C code but I figured there had to be an easier way. Is there?</p> <p>In response to DWin's nice answer I have built a convoluted example where the the regex could fail. This is one of those edge cases where regex scares me.</p> <p>The <code>data.frame</code> is built with variable names and values that can easily be confused which happens a lot.</p> <pre><code>baseball &lt;- data.frame(Bat=sample(1:100, 20, replace=T), Batter=sample(c("David", "Batley", "Bob", "Ace"), 20, replace=T), Hits=sample(1:20, 20, replace=T)) baseball bMod &lt;- lm(Hits ~ Bat*Batter, baseball) bMod$coefficients col.matx &lt;- sapply(colnames(model.matrix(bMod)), function(cols) sapply(labels(bMod), function(trm) grep(patt=trm, x=cols, value=TRUE))) </code></pre> <p>This matches the continuous variable <code>Bat</code> to all the coefficients for the <code>factor</code> <code>Batter</code>.</p> <p>Yes, this is a stupid example, but can easily happen.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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