使用多个条件子集矢量

时间:2012-09-23 00:22:15

标签: r which

> which(LETTERS=="A")
[1] 1
> which(LETTERS=="B")
[1] 2

我可以使用一个语句来获取1,2的值吗?

which(LETTERS=="B" or "A")
Error: unexpected symbol in "which(LETTERS=="B" or"

2 个答案:

答案 0 :(得分:7)

which(LETTERS == "A" | LETTERS == "B")

或者:

which(LETTERS %in% c("A", "B"))

答案 1 :(得分:-1)

作为标题的答案,如何使用多个条件对向量进行子集化:

# Random Data 
  test1 <- sample(x = c(1:30),size = 15,replace = TRUE)
  test2 <- sample(x = c(70:75),size = 15,replace = TRUE)
  test3 <- sample(x = c(1:100),size = 15,replace = TRUE)

# actual data
  # test1
  # [1] 19  1  9  6 15  1 16  4  1 10 11 19 24  1 17
  # test2
  # [1] 71 72 70 74 71 74 74 75 73 73 72 74 74 73 71
  # test3
  # [1] 24 95 66  8  9 97 85  1 40 55 37 84 95 93 95

# subsetting vector 3 with multiple conditons
  test3[test1 > test3 & test2 < 5 * test1]
# [1] 9