replacing `.x` with column name after running `map::purrr()` function

前端 未结 2 1938
孤独总比滥情好
孤独总比滥情好 2021-01-15 13:49

I run lm() for every column of a dataset with one of the column as the dependent variable, using purrr:map() function.

The results are alm

相关标签:
2条回答
  • 2021-01-15 14:48

    Here is one way to do it

    library(tidyverse)
    library(broom)
    
    names(mtcars)[-1] %>% 
      set_names() %>% 
      map(~ lm(as.formula(paste0('mpg ~ ', .x)), data = mtcars)) %>% 
      map_dfr(., broom::tidy, .id = "variable")
    
    #> # A tibble: 20 x 6
    #>    variable term        estimate std.error statistic  p.value
    #>    <chr>    <chr>          <dbl>     <dbl>     <dbl>    <dbl>
    #>  1 cyl      (Intercept)  37.9      2.07       18.3   8.37e-18
    #>  2 cyl      cyl          -2.88     0.322      -8.92  6.11e-10
    #>  3 disp     (Intercept)  29.6      1.23       24.1   3.58e-21
    #>  4 disp     disp         -0.0412   0.00471    -8.75  9.38e-10
    #>  5 hp       (Intercept)  30.1      1.63       18.4   6.64e-18
    #>  6 hp       hp           -0.0682   0.0101     -6.74  1.79e- 7
    #>  7 drat     (Intercept)  -7.52     5.48       -1.37  1.80e- 1
    #>  8 drat     drat          7.68     1.51        5.10  1.78e- 5
    #>  9 wt       (Intercept)  37.3      1.88       19.9   8.24e-19
    #> 10 wt       wt           -5.34     0.559      -9.56  1.29e-10
    #> 11 qsec     (Intercept)  -5.11    10.0        -0.510 6.14e- 1
    #> 12 qsec     qsec          1.41     0.559       2.53  1.71e- 2
    #> 13 vs       (Intercept)  16.6      1.08       15.4   8.85e-16
    #> 14 vs       vs            7.94     1.63        4.86  3.42e- 5
    #> 15 am       (Intercept)  17.1      1.12       15.2   1.13e-15
    #> 16 am       am            7.24     1.76        4.11  2.85e- 4
    #> 17 gear     (Intercept)   5.62     4.92        1.14  2.62e- 1
    #> 18 gear     gear          3.92     1.31        3.00  5.40e- 3
    #> 19 carb     (Intercept)  25.9      1.84       14.1   9.22e-15
    #> 20 carb     carb         -2.06     0.569      -3.62  1.08e- 3
    

    Created on 2019-02-10 by the reprex package (v0.2.1.9000)

    0 讨论(0)
  • 2021-01-15 14:54

    Hi you can use purrr::imap() like so:

    mod3 <- map(mtcars, ~ lm(mpg ~ .x, data = mtcars)) %>%
      map(tidy) %>% 
      imap( ~   {.x[2, 1] <-  .y ; return(.x)}   )
    

    imap sends two things to the function/ formula : .x the item and .y which is either the name of the item (name in this case) or the index. I had to wrap everything in {} in this case to get the assignment to work

    0 讨论(0)
提交回复
热议问题