【问题标题】:Convert a tibble column that is a multi-column-tibble to just a tibble with multiple columns将作为多列 tibble 的 tibble 列转换为仅具有多列的 tibble
【发布时间】:2020-09-02 18:24:09
【问题描述】:

使用dplyr 1.0.0,可以使用dplyr::group_by()dplyr::summarise() 执行以下操作:

tibble(
      x = rnorm(100)
    , y = rnorm(100)
    , z = rep(c(1,2),each=50)
) %>%
    dplyr::group_by(z) %>%
    dplyr::summarize(
        value = as_tibble(prcomp(cur_data())$x)
        , .groups = 'drop'
    ) ->
    out

out 现在有一个名为value 的列,它本身就是一个包含两列的小标题:

> print(out)
# A tibble: 6 x 2
      z value$PC1   $PC2
  <dbl>     <dbl>  <dbl>
1     1    -0.212  3.16 
2     1    -1.02   0.978
3     1    -0.328 -0.419
4     1     1.17  -0.341
5     1    -1.68  -0.775
6     1     0.266 -0.398

> str(out,max=2)
tibble [100 × 2] (S3: tbl_df/tbl/data.frame)
 $ z    : num [1:100] 1 1 1 1 1 1 1 1 1 1 ...
 $ value: tibble [100 × 2] (S3: tbl_df/tbl/data.frame)

然后我将如何将单个 value 列转换为多个列,value tibble 中的每一列对应一个列?

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您可以直接pull 退出,然后bind 继续:

    out %>% bind_cols(pull(., value)) %>% select(-value)
    # A tibble: 100 x 3
           z    PC1     PC2
       <dbl>  <dbl>   <dbl>
     1     1  0.732  0.349 
     2     1 -0.512  1.02  
     3     1  2.44   1.56  
     4     1  1.68  -1.70  
     5     1  1.31   1.20  
     6     1 -1.16  -1.84  
     7     1  0.350 -0.0767
     8     1 -0.611 -1.02  
     9     1 -0.901 -0.638 
    10     1 -0.709  0.0443
    # ... with 90 more rows
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2020-08-02
      • 2021-08-11
      • 1970-01-01
      • 2021-12-10
      • 2018-05-21
      • 2018-11-26
      • 2019-06-24
      • 2020-10-11
      相关资源
      最近更新 更多