[英]How to Split a dataframe column that is a dictionary into two columns
我有一个带有列的数据框,例如
ID | 字典列 |
---|---|
1 | {1:5, 10:15, 3:9} |
2 | {3:4, 5:3} |
... | ... |
我试图让它看起来像:
ID | 可乐 | col_b |
---|---|---|
1 | 1 | 5 |
1 | 10 | 15 |
1 | 3 | 9 |
2 | 3 | 4 |
2 | 5 | 3 |
... | ... | ... |
对此有何建议? 使用stringr
使用了各种方法,但总是stringr
跟踪 ID 列或以混乱和缓慢的循环结束。 谢谢
实现所需结果的tidyverse
方法可能如下所示:
library(dplyr)
library(tidyr)
data.frame(
ID = c(1L, 2L),
dictionary_column = c("{1:5, 10:15, 3:9}", "{3:4, 5:3}")
) %>%
mutate(dictionary_column = gsub("(\\{|\\})", "", dictionary_column)) %>%
separate_rows(dictionary_column, sep = ", ") %>%
separate(dictionary_column, into = c("col_a", "col_b"))
#> # A tibble: 5 × 3
#> ID col_a col_b
#> <int> <chr> <chr>
#> 1 1 1 5
#> 2 1 10 15
#> 3 1 3 9
#> 4 2 3 4
#> 5 2 5 3
不是很优雅,但它有效:
library(tidyr)
library(dplyr)
dat %>%
mutate(dictionary_column = gsub("\\{|\\}|\\,", "", dictionary_column)) %>%
separate(dictionary_column, into=c("a", "b", "c"), sep=" ") %>%
pivot_longer(-ID, values_drop_na=T) %>%
select(-name) %>%
separate(value, into = c("col_a", "col_b"))
# A tibble: 5 × 3
ID col_a col_b
<int> <chr> <chr>
1 1 1 5
2 1 10 15
3 1 3 9
4 2 3 4
5 2 5 3
一个选项str_extract_all
之前和之后的提取数字:
进入list
列,然后unnest
的list
library(stringr)
library(dplyr)
library(tidyr)
df1 %>%
mutate(col_a = str_extract_all(dictionary_column, "\\d+(?=:)"),
col_b = str_extract_all(dictionary_column, "(?<=:)\\d+"),
.keep = "unused") %>%
unnest(c(col_a, col_b))
-输出
# A tibble: 5 × 3
ID col_a col_b
<int> <chr> <chr>
1 1 1 5
2 1 10 15
3 1 3 9
4 2 3 4
5 2 5 3
df1 <- structure(list(ID = 1:2, dictionary_column = c("{1:5, 10:15, 3:9}",
"{3:4, 5:3}")), class = "data.frame", row.names = c(NA, -2L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.