R:在满足两个条件的向量中查找元素
R: Find element in vector that satisfies two conditions
我有一个字符向量。每个元素包含多个 I|J|K|...
类型的值,其中 I, J, K
可能会有所不同并且是其他字符,并且长度未定义。
我有两个值,current
和 next
,我需要找到最后一个管道后的最后一个值等于 next
的向量元素,倒数第二个 current
.
我有下面的例子,但它既不优雅也不快速。
library(stringr)
myVector <- c("a|b|c", "f|o|o", "b|a|r", "f|c|v")
currentValue <- "c"
nextValue <- "v"
for(values in myVector) {
#Split it
split <- strsplit(values, split = "|", fixed = TRUE)[[1]]
# If the penultimate is equal to current
if(split[length(split)-1] == currentValue &
# And the last one is equal to next
split[length(split)] == nextValue) {
# DO SOMETHING
print(values)
}
}
示例 return 正确:[1] "f|c|v"
。可以在这里测试:http://rextester.com/DVD4647
编辑:可能不符合要求(if
的 else
是什么)。在这种情况下,NA
值也可以。
问题
有什么办法可以一行一行地写出来吗?或者用更简单的东西?
我们可以使用正则表达式 grepl
:
pattern = paste0(currentValue, "\|", nextValue, "$")
myVector[grepl(pattern, myVector)]
# [1] "f|c|v"
我们构建模式 "c\|v$"
(使用 c
和 v
的变量)。 $
匹配字符串的末尾,确保匹配是最后一个和倒数第二个值。我们需要用两个反斜杠转义管道 |
,否则它就是正则表达式 OR 运算符。
请注意,如果这些值可能包含其他特殊的正则表达式字符,. \ | ( ) [ { ^ $ * + ?
,它们也需要进行转义。
无需拆分或 for 循环。
我有一个字符向量。每个元素包含多个 I|J|K|...
类型的值,其中 I, J, K
可能会有所不同并且是其他字符,并且长度未定义。
我有两个值,current
和 next
,我需要找到最后一个管道后的最后一个值等于 next
的向量元素,倒数第二个 current
.
我有下面的例子,但它既不优雅也不快速。
library(stringr)
myVector <- c("a|b|c", "f|o|o", "b|a|r", "f|c|v")
currentValue <- "c"
nextValue <- "v"
for(values in myVector) {
#Split it
split <- strsplit(values, split = "|", fixed = TRUE)[[1]]
# If the penultimate is equal to current
if(split[length(split)-1] == currentValue &
# And the last one is equal to next
split[length(split)] == nextValue) {
# DO SOMETHING
print(values)
}
}
示例 return 正确:[1] "f|c|v"
。可以在这里测试:http://rextester.com/DVD4647
编辑:可能不符合要求(if
的 else
是什么)。在这种情况下,NA
值也可以。
问题
有什么办法可以一行一行地写出来吗?或者用更简单的东西?
我们可以使用正则表达式 grepl
:
pattern = paste0(currentValue, "\|", nextValue, "$")
myVector[grepl(pattern, myVector)]
# [1] "f|c|v"
我们构建模式 "c\|v$"
(使用 c
和 v
的变量)。 $
匹配字符串的末尾,确保匹配是最后一个和倒数第二个值。我们需要用两个反斜杠转义管道 |
,否则它就是正则表达式 OR 运算符。
请注意,如果这些值可能包含其他特殊的正则表达式字符,. \ | ( ) [ { ^ $ * + ?
,它们也需要进行转义。
无需拆分或 for 循环。