【问题标题】:Using separate() to split differently-sized strings使用separate() 分割不同大小的字符串
【发布时间】:2023-03-20 00:55:01
【问题描述】:

所以我希望将一个字符串变量分成几部分,但是我将它们分成的子字符串长度不同,而且我没有像 . , |等等所以我从一个数据框开始,比如:

df <- data.frame(x=c("bigApe","smallApe","bigDog","smallDog"),c(1,2,5,3))
x         y
bigApe    1
smallApe  2
bigDog    5
smallDog  3

我希望它以如下形式结束:

  size  anim  y
1 big   Ape   1
2 small Ape   2
3 big   Dog   5
4 small Dog   3

我已经查看了使用 separate() 的东西,它们似乎应该能够做到这一点,但它们似乎都在寻找可预测的分隔符/空白或设置的子字符串长度。我可以将其作为正则表达式来查找大写字母,但它不会保留该字母:

df %>% separate(x,c("size","anim"),sep="[A-Z]")
   size anim num
1   big   pe   1
2 small   pe   2
3   big   og   5
4 small   og   3

我正在寻找的数据没有。我想我可以在 stringr 中添加一些东西,但即使在那里我发现的所有东西似乎都需要指定的字符串长度。我当然可以组合一个可怕的 for 循环,但一定有比这更快的方法!

谢谢!

【问题讨论】:

    标签: r tidyr stringr


    【解决方案1】:

    您还可以使用基本 R 函数 gsub 使用正则表达式组解析原始列。

    df$size <- gsub("([a-z]*)([A-Z]?[a-z]*)", "\\1", df$x)
    df$animal <- gsub("([a-z]*)([A-Z]?[a-z]*)", "\\2", df$x)
    

    【讨论】:

      【解决方案2】:

      我不确定您是否可以使用单独的分隔符保留分隔符...但是您可以使用stringr::str_locate() 查找大写字母的起始位置,然后使用substr(以及一些dplyr 魔术):

      data.frame(x=c("bigApe","smallApe","bigDog","smallDog"),c(1,2,5,3), stringsAsFactors = FALSE) %>%
        rowwise() %>%
        mutate(size = substr(x, 1,stringr::str_locate(x, "[A-Z]")[1]-1),
               animal = substr(x, stringr::str_locate(x, "[A-Z]")[1], nchar(x))
        )
      
      # A tibble: 4 x 4
      # Rowwise: 
        x        c.1..2..5..3. size  animal
        <chr>            <dbl> <chr> <chr> 
      1 bigApe               1 big   Ape   
      2 smallApe             2 small Ape   
      3 bigDog               5 big   Dog   
      4 smallDog             3 small Dog  
      

      【讨论】:

        【解决方案3】:

        你需要这个:

        df %>% separate(x,c("size","anim"), sep = "(?!^)(?=[[:upper:]])")
        
        # A tibble: 4 x 3
          size  anim      y
          <chr> <chr> <dbl>
        1 big   Ape       1
        2 small Ape       2
        3 big   Dog       5
        4 small Dog       3
        

        【讨论】:

          猜你喜欢
          • 2020-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-23
          • 2015-04-13
          • 1970-01-01
          相关资源
          最近更新 更多