rlmsummary

Modify the name of factor variables in lm function(summary function) in r


Sample code:

require(datasets); data(InsectSprays)
model1 <- lm(count ~ spray, data = InsectSprays) 
summary(model1)

When I run above code, the result is enter image description here

However, the levels of spray is not 1,2,3,4,5, they are

enter image description here

I wonder how to display spray1/2/3/4/5 as sprayB/C/D/E/F? I saw other people can get the one showing what I want(display the true levels) with the same code see here:enter image description here


Solution

  • Could you please try the factor as below

    levels(InsectSprays$spray) <- 1:length(levels(InsectSprays$spray))
    
    InsectSprays$spray <- factor(InsectSprays$spray, labels = levels(InsectSprays$spray))
    
    model1 <- lm(count ~ spray, data = InsectSprays) 
    summary(model1)
    
    
    
    Call:
    lm(formula = count ~ spray, data = InsectSprays)
    
    Residuals:
       Min     1Q Median     3Q    Max 
    -8.333 -1.958 -0.500  1.667  9.333 
    
    Coefficients:
                Estimate Std. Error t value Pr(>|t|)    
    (Intercept)  14.5000     1.1322  12.807  < 2e-16 ***
    spray2        0.8333     1.6011   0.520    0.604    
    spray3      -12.4167     1.6011  -7.755 7.27e-11 ***
    spray4       -9.5833     1.6011  -5.985 9.82e-08 ***
    spray5      -11.0000     1.6011  -6.870 2.75e-09 ***
    spray6        2.1667     1.6011   1.353    0.181    
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 3.922 on 66 degrees of freedom
    Multiple R-squared:  0.7244,    Adjusted R-squared:  0.7036 
    F-statistic:  34.7 on 5 and 66 DF,  p-value: < 2.2e-16