0

I am trying to use dplyr::filter to select rows which fall within either of 2 value ranges (1:3 or 7:10) in the Day column.

Ultimately I would like to manipulate df in the MRE below so that it will contain the rows with Day values 1,2,3,7,8,9,10 from the entire data frame, including all IDs.

Trying to use the | operator below produces df2 containing rows with value 1,2,3 for ID "A" only and 7,8,9,10 for ID "B" only.

library("dplyr")

ID <- rep(c("A","B","C"), each = 10)
Day <- rep(c(1:10), times = 3)
Fig <- sample(20:50, 30)

df <- data.frame(ID, Day, Fig)

df2 <- dplyr::filter(df, Day == 1:3 | Day == 7:10)
mda08rds
  • 59
  • 7
  • 1
    Since you're comparing with more than one items, use `%in%` instead of `==`. i.e. `dplyr::filter(df, Day %in% 1:3 | Day %in% 7:10)` – benson23 Mar 07 '23 at 12:48
  • 2
    Learn more in [Test if a vector contains a given element](https://stackoverflow.com/questions/1169248/test-if-a-vector-contains-a-given-element) – benson23 Mar 07 '23 at 12:54

1 Answers1

0

Using %in% instead of == as recommended in the comments by benson23

library("dplyr")

ID <- rep(c("A","B","C"), each = 10)
Day <- rep(c(1:10), times = 3)
Fig <- sample(20:50, 30)

df <- data.frame(ID, Day, Fig)

df2 <- dplyr::filter(df, Day %in% 1:3 | Day %in% 7:10)
mda08rds
  • 59
  • 7