Home > OS >  dplyr::filter error must be a logical vector, not a character
dplyr::filter error must be a logical vector, not a character

Time:11-11

I am trying to filter a dataframe based on multiple ID values from a column ID which has a character datatype. When I run the code with | (AND) boolean I get an error.

How can I fix this in R using dplyr

Sample data

ID      Date     Var1 Var2  
279557  1/1/2020 1    2
280485  1/2/2020 3    4
279556  1/3/2020 5    6
280484  1/4/2020 7    8
267254  1/5/2020 9    10
290512  1/6/2020 11   12

Code

library(dplyr)

df = df%>% 
  filter(df, ID== '279557' | ID == '280485' | ID == '279556' | ID == '280484')

Error:

x Input `..1$ID` must be a logical vector, not a character.

I know I can create a dataframe of the target IDs and do something like shown below.

Is this the only way doing this with dplyr::filter and boolean conditions?

target = c("29557", "280485", "279556", "280484")
df = df%>% 
      filter(df$ID %in% target)

CodePudding user response:

I think you do not need to reference the dataframe in the call to filter:

df <- data.frame(
  ID = 1:10
)

df = df %>% 
  filter(ID== '1' | ID == '5' | ID == '9')
df
  ID
1  1
2  5
3  9
  • Related