【问题标题】:Split delimited strings in multiple columns and separate them into rows将分隔的字符串拆分为多列并将它们分成行
【发布时间】:2021-10-18 04:50:52
【问题描述】:

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

【问题讨论】:

  • | 是正则表达式中的特殊字符。试试tidyr::separate_rows(to_expand, second, sep = '\\|')
  • 嗨@RonakShah,使用separate_rows(second, sep = '\\|') 在两行都给了我a~b。如何将a 保留在第一行,将b 保留在第二行?

标签: r dplyr tidyr


【解决方案1】:

如果我们使分隔符相同,我们可以更简单地做到这一点

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 

【讨论】:

    【解决方案2】:

    如果要将这些列分成相同数量的行,您可以同时在多个列上使用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 
    

    【讨论】:

      【解决方案3】:

      也许更透明的模式是这样的:

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

      如果有的话,我们separate_rows要么

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

      【讨论】:

        【解决方案4】:

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

        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 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多