首页 > 解决方案 > R - 使用 stringr::str_split 合并两个列表中的唯一值

问题描述

我有一个函数,当给定一个字符串列表时,它应该返回一个包含所有 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 很陌生,所以我很难理解我哪里出错了。

标签: rstringrstrsplit

解决方案


我们可以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")

推荐阅读