【问题标题】:How to split a string in multiple part using first bracket in R?如何使用R中的第一个括号将字符串拆分为多个部分?
【发布时间】:2021-11-19 04:37:18
【问题描述】:

我有类似 -

的字符串
st1<- c("realme C20 (Cool Blue, 32 GB)")
st2<- c("realme C11 (2021) (Cool Grey, 2GB RAM, 32GB Storage)")

我想拆分 s.t.我的输出为 -

output1
[1] "realme C20"       "Cool Blue, 32 GB" "NA"
output2
[1] "realme C11"       "2021"             "Cool Grey, 2GB RAM, 32GB Storage"

我完全不知道如何进行。

【问题讨论】:

    标签: r string split


    【解决方案1】:

    正则表达式是我的弱点,但也许这对你有帮助:

    library(stringr)
    library(dplyr)
    
    
    str_split(st1,"\\(|\\)") %>% unlist()
    [1] "realme C20 "      "Cool Blue, 32 GB" ""                
    
    str_split(st2,"\\(|\\)") %>% unlist()
    [1] "realme C11 "                      "2021"                            
    [3] " "                                "Cool Grey, 2GB RAM, 32GB Storage"
    [5] ""
    

    如果"" 无关紧要,你也可以删除它们

    【讨论】:

      【解决方案2】:

      基本 R 选项 -

      使用 gsub 删除右括号 ()) 并在左括号 (() 上拆分字符串。

      split_string <- function(st) {
        trimws(strsplit(gsub('\\)', '', st), '\\(')[[1]])  
      }
      
      split_string(st1)
      #[1] "realme C20"       "Cool Blue, 32 GB"
      
      split_string(st2)
      #[1] "realme C11"  "2021"   "Cool Grey, 2GB RAM, 32GB Storage"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-25
        • 1970-01-01
        • 1970-01-01
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多