首页 > 解决方案 > 将作为多列 tibble 的 tibble 列转换为仅具有多列的 tibble

问题描述

有了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为多列,每列对应valuetibble 中的每一列?

标签: rdplyrtidyverse

解决方案


你可以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

推荐阅读