【问题标题】:R - Merge unique values from two lists using stringr::str_splitR - 使用 stringr::str_split 合并两个列表中的唯一值
【发布时间】:2020-11-23 23:43:42
【问题描述】:

我有一个函数,当给定一个字符串列表时,它应该返回一个包含所有 N 大小的唯一字符串的向量。

get_unique <- function (input_list, size = 3) {
   output = c()

   for (input in input_list) {
    current = stringr::str_replace(input, "[-_\\s]", "")
    current = trimws(gsub(paste0("(.{",size,"})"), "\\1 ", current))
    parts = stringr::str_split(current, "\\s", simplify = TRUE)[1,]
    output = union(output, parts)
   }

   return(output)
}

我的期望是:

get_unique(c("ABC", "ABCDEF", "GHIDEF"))

[1] "ABC" "DEF" "GHI"

但我得到的是:

get_unique(c("ABC", "ABCDEF", "GHIDEF"))

[[1]]
[1] "ABC"

[[2]]
[1] "DEF"

[[3]]
[1] "GHI"

我对 R 还很陌生,所以我很难理解我哪里出错了。

【问题讨论】:

    标签: r stringr strsplit


    【解决方案1】:

    我们可以在最后使用unlist

    get_unique <- function (input_list, size = 3) {
      output = c()
    
      for (input in input_list) {
         current = stringr::str_replace(input, "[-_\\s]", "")
         current = trimws(gsub(paste0("(.{",size,"})"), "\\1 ", current))
        parts = stringr::str_split(current, "\\s", simplify = TRUE)[1,]
        output = union(output, parts)
      }
    
      return(unlist(output))
     }
    
    get_unique(c("ABC", "ABCDEF", "GHIDEF"))
    #[1] "ABC" "DEF" "GHI"
    

    我们也可以在一行中使用正则表达式环视来执行此操作,以便在每 3 个字符处拆分

    unique(unlist(strsplit(v1, "(?<=...)", perl = TRUE)))
    #[1] "ABC" "DEF" "GHI"
    

    数据

    v1 <- c("ABC", "ABCDEF", "GHIDEF")
    

    【讨论】:

    • @akrun 您能否简要解释一下regex 中发生了什么?
    【解决方案2】:

    完整的baseR 解决方案,使用substr

    get_unique <- function(v) unique(unlist(sapply(v, function(x) sapply(1:(nchar(x)/3), function(y) substr(x, 3*(y-1)+1, 3*y) ))))
    
    get_unique(v1)
    [1] "ABC" "DEF" "GHI"
    
    • substr(x, 3*(y-1)+1, 3*y) 从 x 中获取 3 个字符的子字符串。

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      相关资源
      最近更新 更多