R语言 将列表名称作为行名称的列表合并[重复]

dluptydi  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(108)

此问题已在此处有答案

Add the index of list to bind_rows?(2个答案)
Create a column based on the name of the element list that contain the data frame in R(2个答案)
Not getting list names as row names in do.call [duplicate](2个答案)
Adding a column to every dataframe in a list with the name of the list element(2个答案)
6天前关闭。
在执行拆分和回归之后,我想将这些列表合并到一个 Dataframe 中,并将列表名称作为行名称。任何建议。

lapply(split(mtcars, mtcars$cyl), \(x) lm(mpg ~ disp, data = x)) |> 
  lapply(\(x) broom::tidy(x))
#> $`4`
#> # A tibble: 2 × 5
#>   term        estimate std.error statistic    p.value
#>   <chr>          <dbl>     <dbl>     <dbl>      <dbl>
#> 1 (Intercept)   40.9      3.59       11.4  0.00000120
#> 2 disp          -0.135    0.0332     -4.07 0.00278   
#> 
#> $`6`
#> # A tibble: 2 × 5
#>   term        estimate std.error statistic p.value
#>   <chr>          <dbl>     <dbl>     <dbl>   <dbl>
#> 1 (Intercept) 19.1        2.91       6.55  0.00124
#> 2 disp         0.00361    0.0156     0.232 0.826  
#> 
#> $`8`
#> # A tibble: 2 × 5
#>   term        estimate std.error statistic   p.value
#>   <chr>          <dbl>     <dbl>     <dbl>     <dbl>
#> 1 (Intercept)  22.0      3.35         6.59 0.0000259
#> 2 disp         -0.0196   0.00932     -2.11 0.0568

所需输出:

cyl term        estimate std.error statistic    p.value
  <dbl> <chr>          <dbl>     <dbl>     <dbl>      <dbl>
1     6 (Intercept) 19.1       2.91        6.55  0.00124   
2     6 disp         0.00361   0.0156      0.232 0.826     
3     4 (Intercept) 40.9       3.59       11.4   0.00000120
4     4 disp        -0.135     0.0332     -4.07  0.00278   
5     8 (Intercept) 22.0       3.35        6.59  0.0000259 
6     8 disp        -0.0196    0.00932    -2.11  0.0568

创建于2023-04-27带有reprex v2.0.2

q8l4jmvw

q8l4jmvw1#

试试data.table::rbindlist

lapply(split(mtcars, mtcars$cyl), \(x) lm(mpg ~ disp, data = x)) |>
  lapply(\(x) broom::tidy(x)) %>%
  data.table::rbindlist(idcol = "cyl")

它给出了

cyl        term     estimate   std.error  statistic      p.value
1:   4 (Intercept) 40.871955322 3.589605400 11.3861973 1.202715e-06
2:   4        disp -0.135141815 0.033171608 -4.0740206 2.782827e-03
3:   6 (Intercept) 19.081987419 2.913992892  6.5483988 1.243968e-03
4:   6        disp  0.003605119 0.015557115  0.2317344 8.259297e-01
5:   8 (Intercept) 22.032798914 3.345241115  6.5863112 2.588765e-05
6:   8        disp -0.019634095 0.009315926 -2.1075838 5.677488e-02

相关问题