gpt4 book ai didi

R - 使用 stringr::str_split 合并两个列表中的唯一值

转载 作者:行者123 更新时间:2023-12-03 08:31:24 27 4
gpt4 key购买 nike

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

最佳答案

我们可以在最后使用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")

关于R - 使用 stringr::str_split 合并两个列表中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64978248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com