我有一个矢量,
myvector <- c("a","b","c","cat","4","dog","cat","f")
。我想选择那些紧跟在包含字符串&#34; cat&#34;的元素之后的元素。
即,我希望myvector2
仅包含&#34; 4&#34;和&#34; f&#34;。我不知道从哪里开始。
答案 0 :(得分:6)
myvector <- c("a","b","c","cat","4","dog","cat","f")
where_is_cat <- which(myvector == "cat")
# [1] 4 7
myvector[where_is_cat + 1]
# [1] "4" "f"
myvector2 <- myvector[where_is_cat + 1]
答案 1 :(得分:2)
试试这个:
x[grep('cat',x)+1]
#[1] "4" "f"
答案 2 :(得分:1)
您可以通过索引来减去第一个元素(list[-1]
)的子集列表,其中列表减去其最后一个元素(list[-length(list)]
)等于&#34; cat&#34;
list[-1][list[-length(list)]=="cat"]
# [1] "4" "f"