r - 整理数据:从包含向量的单元格到列
问题描述
我有一个小标题,其中包含用于主题的双精度向量(例如motif_1
和motif_2
):
table <- tibble(ID = c(1,2,3,4,5),
motif_1 = list(c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10))),
motif_2 = list(c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10)), c(runif(n = 5, min = 0, max = 10))))
# A tibble: 5 x 3
ID motif_1 motif_2
<dbl> <list> <list>
1 1 <dbl [5]> <dbl [5]>
2 2 <dbl [5]> <dbl [5]>
3 3 <dbl [5]> <dbl [5]>
4 4 <dbl [5]> <dbl [5]>
5 5 <dbl [5]> <dbl [5]>
我想做的是在关于向量长度的数字中创建列(总是 5,所以P1
... P5
),向量的值将被分配到与向量中的特定位置相对应的值。
总的来说会导致这个输出:
# A tibble: 10 x 7
ID motif P1 P2 P3 P4 P5
<dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 motif_1 2.61 4.19 0.182 4.26 5.60
2 2 motif_1 5.88 5.24 5.97 3.26 0.390
3 3 motif_1 6.86 1.25 9.98 4.56 2.93
4 4 motif_1 3.02 8.99 7.33 8.12 4.18
5 5 motif_1 2.40 6.61 6.35 8.42 0.202
6 1 motif_2 2.39 7.12 7.61 3.83 0.506
7 2 motif_2 5.20 3.09 5.53 1.52 6.05
8 3 motif_2 3.97 2.90 5.94 6.85 2.99
9 4 motif_2 8.37 5.35 3.84 1.88 0.358
10 5 motif_2 6.53 2.78 8.59 1.57 4.90
更具体地说,只考虑输入表的第一行:
FROM:
# A tibble: 5 x 3
ID motif_1 motif_2
<dbl> <list> <list>
1 1 c(2.61, 4.19, 0.182, 4.26, 5.60) <dbl [5]>
TO:
ID motif P1 P2 P3 P4 P5
<dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 motif_1 2.61 4.19 0.182 4.26 5.60
2 1 motif_2 ...
提前感谢您的任何建议。
解决方案
这是一种tidyverse
方法 -
library(dplyr)
library(tidyr)
table %>%
unnest(cols = starts_with('motif')) %>%
pivot_longer(cols = -ID) %>%
group_by(ID, name) %>%
mutate(col = paste0('P', row_number())) %>%
ungroup %>%
pivot_wider(names_from = col, values_from = value)
# ID name P1 P2 P3 P4 P5
# <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 motif_1 1.52 1.39 2.33 4.66 2.66
# 2 1 motif_2 4.40 7.54 6.29 7.10 0.00625
# 3 2 motif_1 8.58 0.458 4.42 7.99 1.22
# 4 2 motif_2 4.75 2.20 3.80 6.13 3.52
# 5 3 motif_1 5.61 2.07 1.28 7.53 8.95
# 6 3 motif_2 1.11 2.44 6.68 4.18 7.88
# 7 4 motif_1 3.74 6.65 0.948 3.84 2.74
# 8 4 motif_2 1.03 4.35 9.85 8.93 8.86
# 9 5 motif_1 8.15 4.49 8.10 8.12 7.94
#10 5 motif_2 1.75 1.31 6.53 3.44 6.57
推荐阅读
- javascript - Cookie 未由 Chrome 和 withCredentials 发送是真的
- repository-pattern - 尝试激活“Api.ServicesBusiness.EquipoServices”时无法解析“Api.Repositories.UnitOfWork”类型的服务
- javascript - 如何将变量发送到 php 文件
- amazon-web-services - 向规范 ID 授予权限时 API `aws s3` 和 `aws s3api` 之间的区别
- java - 尝试设置旧版 Java Spring 引导应用程序时无法解决导入 com.fasterxml.jackson 错误
- apache-spark - RDD 的 .first() 方法是否洗牌?
- ios - 如何在 SwiftUI 中为图像设置动画,播放帧动画
- jquery - Laravel - 如何在 Laravel 中使用 jQuery AJAX ( $.ajax({}) ) 来执行特定操作?
- powershell-2.0 - 如何使用 PowerShell 在 Windows 7 上自动登录多个用户帐户?
- python - 有没有办法让输出中心本身在 tkinter 中?