r - 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 很陌生,所以我很难理解我哪里出错了。
解决方案
我们可以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")
推荐阅读
- python - 如何获取 index.cuda?
- python - 循环遍历 Pandas 数据并通过 2 个输入(lat long)找到最大值过滤器
- python - Python:FileNotFoundError:[Errno 2] 没有这样的文件或目录:
- amazon-web-services - 如何触发 AWS Lambda 函数错误以测试 Cloudwatch 警报
- r - 找不到对象“世界”
- android - java.lang.illegalStateException: 预期 BEGIN_OBJECT 但在第 1 行第 1 列路径为字符串 $ Rest api Gives OnFailed
- python - Python:ValueError:无法将字符串转换为浮点数:'44,052,037.79'
- python - 如何正确使用 key=operator.itemgetter() 对数据进行正确排序?
- python - argparse:将无法识别的选项视为位置?
- actionscript-3 - 从 AIR 中启动 Inno Setup Update