Subsetting a vector using multiple conditions

2019-08-03 09:36发布

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

Can i use one statement in which to get the value of 1,2?

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

标签: r which
2条回答
等我变得足够好
2楼-- · 2019-08-03 09:48
which(LETTERS == "A" | LETTERS == "B")

Or:

which(LETTERS %in% c("A", "B"))
查看更多
老娘就宠你
3楼-- · 2019-08-03 10:02

as answer for the title, how subsetting a vector using multiple conditions:

# 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
查看更多
登录 后发表回答