我正在寻找一种单向视图,以显示斜率和截距之间的比率。
到目前为止,我有:
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% map_dbl("(Intercept)")
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% map_dbl("wt")
这可以工作并根据需要打印截距和斜率,但我似乎都不能进行任何计算。
我已经尝试了以下方法来获得两者之间的比例。
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% map_dbl("wt")/map_dbl("(Intercept)")
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% map_dbl("wt"/"(Intercept)")
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% map_dbl(map_dbl("wt")/map_dbl("(Intercept)"))
任何帮助表示感谢,谢谢。
没有purrr,但带有扫帚的另一种方式:
library(broom)
library(dplyr)
mtcars %>% group_by(cyl) %>%
do(tidy(lm(mpg~wt, data =.))) %>%
summarize(ratio=estimate[2]/estimate[1])
# A tibble: 3 x 2
cyl ratio
<dbl> <dbl>
1 4 -0.143
2 6 -0.0979
3 8 -0.0919
使用名称对当前元素.
/ .x
进行细分,然后使用~
创建除法公式
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map_dbl(~.[["coefficients"]][["wt"]]/.[["coefficients"]][["(Intercept)"]]) #%>%
#enframe(name = "cyl", value = "ratio") #produces output as a data.frame
4 6 8
-0.14270545 -0.09786058 -0.09185668
为了使您的方法可行,我们可以使用{}
mtcars %>% split(.$cyl) %>%
map(~lm(mpg~wt, data =.)) %>%
map(coefficients) %>% {map_dbl(.,"wt")/map_dbl(.,"(Intercept)")}