我想从字符向量中获取一个子集。但是我想从特定元素之间的初始向量中获取包含元素的vector2。
vector <- c("a", "", "b", "c","","d", "e")
vector
如何获取元素“ b”和“ e”之间的所有元素并获取vector2?
#Expected result:
vector2
"c","","d"
答案 0 :(得分:2)
这是一个选择
f <- function(x, left, right) {
idx <- x %in% c(left, right)
x[as.logical(cumsum(idx) * !idx)]
}
f(vector, "b", "e")
# [1] "c" "" "d"
第一步是将idx
计算为
vector %in% c("b", "e")
# [1] FALSE FALSE TRUE FALSE FALSE FALSE TRUE
然后计算累计和
cumsum(vector %in% c("b", "e"))
# [1] 0 0 1 1 1 1 2
乘以!vector %in% c("b", "e")
,得出
cumsum(vector %in% c("b", "e")) * !vector %in% c("b", "e")
# [1] 0 0 0 1 1 1 0
将其转换为逻辑向量,并将其用于x
的子集。
对于给定的示例,另一个选项是charmatch
x <- charmatch(c("b", "e"), vector) + c(1, -1)
vector[seq.int(x[1], x[2])]
# [1] "c" "" "d"
答案 1 :(得分:1)
您还可以执行以下操作:
vector <- c("a", "", "b", "c","","d", "e")
vector[seq(which(vector=="b")+1,which(vector=="e")-1)]
#[1] "c" "" "d"
答案 2 :(得分:0)
带下标:
x[-c(1:which(x == 'b'), which(x =='e'):length(x))]
#[1] "c" "" "d"
如果在e
之前找到b
,则返回空向量:
(y <- rev(x))
#[1] "e" "d" "" "c" "b" "" "a"
y[-c(1:which(y == 'b'), which(y =='e'):length(y))]
#character(0)
答案 3 :(得分:0)
您也可以尝试:
vector[cumsum(vector %in% c("b", "e")) == 1][-1]
[1] "c" "" "d"