r - 将作为多列 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
为多列,每列对应value
tibble 中的每一列?
解决方案
你可以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
推荐阅读
- file - 如何在运行 rust 二进制文件之间将文件保存在内存中?
- firebase - 在 Flutter 列表视图中删除 Firestore 数据
- java - 尝试在后台线程上使用 Toast.hide 时出现 IllegalStateException
- python - 有没有办法在 Django 应用程序之外使用反向?
- excel - 为什么没有应用我的 VBE 颜色主题?
- ios - SwiftUI 如何实现 VKPinCodeView
- discord.js - Discord.js 如何添加角色
- python - 如何根据采样率在 Python 中按顺序对数组进行均匀采样?
- google-app-engine - post-install-cmd 在 Google App Engine 柔性环境中不起作用
- ruby - 如何比较来自两个不同数组的元素?红宝石