How to vectorize extracting significant predictor variables?
r
Solution
`names(sig)[sig <= 0.05]` is what you are looking for. `names(sig)` returns all the names and `sig <= 0.05` helps to extract a desirable subset.
Problem
I run `glm` and get the results ok. Now I would like to get the name of those predictors that are significant at 95% i.e. p-value is less or equal to significance level 5e-2. I run: ``` fit <- glm(data=dfa, formula=response~.) sig <- summary(fit)$coefficients[,4] (Intercept) close0 close1 close2 close3 close4 closema open0 0.000000e+00 3.147425e-19 7.210909e-04 1.046019e-02 4.117580e-03 2.778701e-01 2.829958e-05 0.000000e+00 open1 open2 open3 open4 openma low0 low1 low2 8.627202e-30 1.138499e-02 1.112236e-03 7.422145e-03 3.967735e-03 3.036329e-42 3.033847e-05 3.237155e-01 low3 low4 lowma high0 high1 high2 high3 high4 8.198750e-01 6.647138e-02 4.350488e-05 6.177130e-58 2.625192e-02 4.143373e-01 3.964651e-01 3.694272e-01 highma volume0 volume1 volume2 volume3 volume4 volumema 1.416310e-05 8.027502e-02 1.975302e-01 1.630341e-09 8.979313e-03 1.274195e-06 8.246661e-01 > str(sig) Named num [1:31] 0.00 3.15e-19 7.21e-04 1.05e-02 4.12e-03 ... - attr(*, "names")= chr [1:31] "(Intercept)" "close0" "close1" "close2" ... ``` What is that "Named num" type anyway? I would like to have an array of column names like this because those predictor variables have p-value below significance level 5e-2 i.e. ``` best <- c('close0', 'close1', 'close2', 'close3', 'closema', ... etc) ``` Note the `close4` is not there ... How can I extract these column names in a vectorized fashion? UPDATE: I worked out how to do it in a loop ``` fit <- glm(data=dfa, formula=response~.) summary(fit) sig <- summary(fit)$coefficients[,4] best <- NULL columnLabels <- names(sig) for (columnLabel in columnLabels) { if (as.numeric(sig[columnLabel]) <= 5e-2) { if (is.null(best)) { best <- columnLabel } else { best <- c(best, columnLabel) } } } ```