给出一个字符串:
vals <- "-AB, CV, CL, -TS"
我希望有效地将vals
解析为两个向量(让我们称之为negative
和positive
),其中一个包含前缀为{{1}的值其他没有。一个问题是我还想删除-
指标。
期望的结果:
-
紧凑答案的奖励积分。
答案 0 :(得分:2)
您可以尝试:
s <- trimws(strsplit(vals, ",")[[1]])
negative <- s[grepl("^-", s)]
positive <- s[!grepl("^-", s)]
或者你可以这样使用纯正则表达式
library(stringr)
negative <- as.vector(str_match_all(vals, "-\\w+")[[1]])
positive <- as.vector(str_match_all(vals, "(?<!-)(?<=^|,| )\\w+")[[1]])
答案 1 :(得分:1)
尝试:
v <- trimws(strsplit(vals, ",")[[1]])
positive <- v[!startsWith(v, '-')]
negative <- substring(v[startsWith(v, '-')], 2)
哪个输出:
> negative
[1] "AB" "TS"
> positive
[1] "CV" "CL"
答案 2 :(得分:1)
您可以尝试将grep
与value = True
选项一起使用,因为您的数据有前导空格,要删除它们,您可以使用trimws
。我在这里使用strsplit
&#34;,&#34;作为分隔符。使用zeallot
库只需一步分配所有内容。
library(zeallot)
c(negative, positive) %<-% list(grep("^-",trimws(strsplit(vals,",")[[1]]), value=T), grep("^[^-]",trimws(strsplit(vals,",")[[1]]), value=T))
<强>输出强>:
#> negative
#[1] "-AB" "-TS"
#> positive
#[1] "CV" "CL"