darkace
darkace

Reputation: 878

Shortening multiple or conditions

Hope I'm not being extremely lazy here but I was wondering whether there was a way to shorten this condition

dataframe[holiday == 'Yes' & ( type == 1 | type == 2 | type == 3 ), ]

I think the syntax is wrong here, but what I'm trying to do is show all people that have been on a holiday and have chosen either type 1, 2 or 3.

Upvotes: 1

Views: 117

Answers (2)

vrajs5
vrajs5

Reputation: 4126

lets say dataframe is df then it would be

df[(df$holiday == 'Yes') & (df$type %in% c(1, 2, 3)), ]

Upvotes: 3

Scott Ritchie
Scott Ritchie

Reputation: 10543

Your syntax is wrong if holiday and type are columns of that data.frame: [.data.frame doesn't evaluate its contents within scope, meaning this doesn't make sense unless holiday and type are variables in the global environment. Instead I suspect you mean this:

dataframe[dataframe$holiday == 'Yes' & 
         (dataframe$type == 1 | dataframe$type == 2 | dataframe$type = 3),]

Rather than using mulitple OR statements, its much more concise to use %in%:

dataframe[dataframe$holiday == 'Yes' & dataframe$type %in% 1:3,]

However the data.table library DOES evaluate the column names in the scope of data.table, allowing you to go back to your original syntax:

require(data.table)
dt <- as.data.table(data.frame)
dt[holiday == 'Yes' & type %in% 1:3,]

Upvotes: 2

Related Questions