在多列中拆分定界字符串并将它们分隔成行

Split delimited strings in multiple columns and separate them into rows

我有这个数据框 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

我尝试使用 tidyr 中的 sepratate_rows(),但它给出了两列之间所有可能的组合。

如有任何帮助,我们将不胜感激!


编辑:使用 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 

您可以为不同的列传递不同的分隔符。

purrr::map2_df(to_expand, c('~', '|'), ~strsplit(.x, .y, fixed = TRUE)[[1]])

#  first second
#  <chr> <chr> 
#1 a     1~2~3 
#2 b     4~5~6 

如果要将这些列分成相同数量的行,您可以同时对多个列使用 tidyr::separate_rows()

to_expand %>%
   separate_rows(first, second, sep = "(?<=\D)~|(?<=\d)\|")

# A tibble: 2 x 2
  first second
  <chr> <chr> 
1 a     1~2~3 
2 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 

一个可能更透明的模式是这样的:

to_expand %>%
  separate_rows(first, second, sep = "(?<=[a-z])~|\|")

这里我们separate_rows要么如果有

  • a ~ 如果左边有一个小写字母或者如果有
  • 一个|