我有这个数据框 to_expand
有两列:
to_expand <- data.frame(first = c('a~b'), second = paste(list(c('1~2~3'), c('4~5~6')), collapse = '|'))
first second
1 a~b 1~2~3|4~5~6
我怎样才能把它变成:
# A tibble: 2 x 2
first second
<chr> <chr>
1 a 1~2~3
2 b 4~5~6
我尝试过使用 sepratate_rows()
来自 tidyr
但它给出了两列之间所有可能的组合。
任何帮助将不胜感激!
编辑:使用 separate_rows(second, sep = '\\|')
给了我a~b
两行。
> to_expand %>% separate_rows(second, sep = '\\|')
# A tibble: 2 x 2
first second
<chr> <chr>
1 a~b 1~2~3
2 a~b 4~5~6
最佳答案
如果我们使分隔符相同,我们可以更简单地做到这一点
library(dplyr)
library(tidyr)
library(stringr)
to_expand %>%
mutate(first = str_replace(first, "~", "|")) %>%
separate_rows(first, second, sep = "\\|")
# A tibble: 2 x 2
first second
<chr> <chr>
1 a 1~2~3
2 b 4~5~6
关于r - 将分隔的字符串拆分为多列并将它们分成行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68797695/