[英]Slope/Intercept ratio with Purr in R
我正在尋找打印斜率和截距之間比率的單向視圖。
到目前為止我有:
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)"))
任何幫助表示贊賞,謝謝。
子集當前元素.
/ .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)")}
另一種沒有呼嚕聲但有掃帚的方式:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.