Mike Lawrence
Mike Lawrence

Reputation: 1701

Convert a tibble column that is a multi-column-tibble to just a tibble with multiple columns

With dplyr 1.0.0, it's become possible to use dplyr::group_by() and dplyr::summarise() to do the following:

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

Where out now has a column called value that itself is a tibble with two columns:

> 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)

How would I then go about converting that single value column to multiple columns, one for each column in the value tibble?

Upvotes: 0

Views: 270

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You could just pull it out and bind it on:

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

Upvotes: 1

Related Questions