0

What is the '|' symbol in R, how is it different from '||' (logical OR) and when should it be used?

I'm trying to create a subset of a data.table and I write midwest = DT[State == "WI" || State == "MI" || State == "IL" || State == "MN"] it produces a table with just columns and no rows, but when I write midwest = DT[State == "WI" | State == "MI" | State == "IL" | State == "MN"] I get the subset I'm looking for with it's rows filled.

Vito
  • 680
  • 1
  • 7
  • 23
  • 3
    from the docs: "& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses." – blep Sep 11 '15 at 19:27
  • 3
    You probably want to use `%in%`, like `DT[State %in% c("WI","MN")]` – Frank Sep 11 '15 at 19:34

0 Answers0