r - 使用列表值拆分列并收集到 r
问题描述
我有这个df:
>df
author author_id other_authors other_authors_id
A 123 D, E ,F 011 , 021, 003
B 122 G 111
C 121 H, F 101, 003
最后两列的值存储为list
. 我想让它从宽到长,但我不确定最好的方法是什么。我正在尝试从中创建网络图。
我想收集它们,使它们看起来像这样:
author other_autors author_id other_autors_id
A D 123 011
A E 123 021
A F 123 003
B G 122 111
C H 121 101
C F 121 003
任何想法怎么做?我已经设法做到这一点,但它只有在值不是时才有效lists
。
gather(df, key="author", value="other_authors", -author)
解决方案
我们可以使用cSplit
fromsplitstackshape
进行多列拆分
library(splitstackshape)
cSplit(df, c("other_authors", "other_authors_id"), ", ", "long",
fixed = FALSE, type.convert = FALSE)
# author author_id other_authors other_authors_id
#1: A 123 D 011
#2: A 123 E 021
#3: A 123 F 003
#4: B 122 G 111
#5: C 121 H 101
#6: C 121 F 003
或使用separate_rows
fromtidyr
library(tidyverse)
df %>%
separate_rows(other_authors, other_authors_id)
# author author_id other_authors other_authors_id
#1 A 123 D 011
#2 A 123 E 021
#3 A 123 F 003
#4 B 122 G 111
#5 C 121 H 101
#6 C 121 F 003
更新
如果列 'other_authors', 'others_authors_id' 是list
列,那么我们可以使用unnest
df1 %>%
unnest
# author author_id other_authors other_authors_id
#1 A 123 D 011
#2 A 123 E 021
#3 A 123 F 003
#4 B 122 G 111
#5 C 121 H 101
#6 C 121 F 003
数据
df <- structure(list(author = c("A", "B", "C"), author_id = 123:121,
other_authors = c("D, E ,F", "G", "H, F"), other_authors_id = c("011 , 021, 003",
"111", "101, 003")), class = "data.frame", row.names = c(NA,
-3L))
df1 <- structure(list(author = c("A", "B", "C"), author_id = 123:121,
other_authors = list(c("D", "E", "F"), "G", c("H", "F")),
other_authors_id = list(c("011", "021", "003"), "111", c("101",
"003"))), row.names = c(NA, -3L), class = "data.frame")
推荐阅读
- spring - 跨域不起作用
- r - 如何在R中选择具有特定日期的每一行
- javascript - 在 Typescript 对象中添加新属性
- wordpress - Wordpress 添加自定义布尔值列
- php - ajax 响应数据始终未定义
- python-3.x - 我想使用 python 的 opencv 分割大小为 32x32px 或更大的补丁
- amazon-web-services - 允许对 S3 存储桶进行开放访问,但有一定的限制
- multithreading - 非读和非写指令在 x86 中重新排序是否重要?
- python - 如何使用 R-FCN 模型在 tensorflow 库中获取位置敏感分数图?
- node.js - npm 从本地工件存储库中获取工件