Reputation: 18198
I have the following code which displays some coefficients from lm
fit <-lm(Petal.Width ~ Petal.Length, data=iris)
cf <-coef(summary(fit,complete = TRUE))
colnames(cf)[4] <- "pval"
cf<- data.frame(cf)
cf <-cf[cf$pval < 0.05,]
cf <-cf[order(-cf$pval), ]
head(cf)
cf[1,1]
I want to extract the names in the left column ie (intercept) and petal length. I thought I could use cf[1,1] but it shows the estimate
Upvotes: 0
Views: 2357
Reputation: 866
The tidyverse
solution would be to use broom
:
library(broom)
tidy_fit <- tidy(fit)
Results:
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) -0.363 0.0398 -9.13 4.70e-16
2 Petal.Length 0.416 0.00958 43.4 4.68e-86
Then it's easy to extract the components that you want and the resulting code is more readable, e.g. tidy_fit$term
to get the list of variables ((Intercept)
and Petal.Length
).
Upvotes: 1
Reputation: 389315
Those are extracted using rownames
:
fit <-lm(Petal.Width ~ Petal.Length, data=iris)
cf <-coef(summary(fit,complete = TRUE))
rownames(cf)
#[1] "(Intercept)" "Petal.Length"
Upvotes: 1