filtering or subsetting a dataframe does not include all values

Viewed 135

I have a dataframe and I'm trying to subset it based on the column ID, but because the ID values are repeated, not all values are included in the output.

Example:

values <- sample(1:100, 2520, replace=TRUE)
ID <- rep(c(1:21), times = 120) #21 unique IDs, each repeated 120 times
df <- data.frame(values, ID)


df_sub <- df %>% dplyr::filter(ID == c(1,2,5,7,9))

It's subsetting by ID correctly, but I am only getting 24 rows for each ID and not the 120 I am expecting.

length(df_sub$ID) = 120 and should be 600.

1 Answers

We can use %in% instead of == as == is elementwise operator and can only with a single element or the lengths shsould be same on the lhs and rhs of ==

library(dplyr)
df %>% 
    dplyr::filter(ID %in% c(1,2,5,7,9))
Related