R中具有Purr的斜率/截距比

问题描述 投票:1回答:2

我正在寻找一种单向视图,以显示斜率和截距之间的比率。

到目前为止,我有:

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)"))

任何帮助表示感谢,谢谢。

r dplyr tidyverse purrr lm
2个回答
1
投票

没有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

1
投票

使用名称对当前元素. / .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)")}
© www.soinside.com 2019 - 2024. All rights reserved.