选择R中向量中的特定元素

时间:2015-06-16 22:50:08

标签: r

我有一个矢量, myvector <- c("a","b","c","cat","4","dog","cat","f")。我想选择那些紧跟在包含字符串&#34; cat&#34;的元素之后的元素。

即,我希望myvector2仅包含&#34; 4&#34;和&#34; f&#34;。我不知道从哪里开始。

3 个答案:

答案 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"