-1

I am filtering a dataset and this chunk works fine:

    dwell <- rail %>% 
  filter_(Measure == "Average Terminal Dwell Time (Excluding Cars on Run Through Trains) (Hours)",
         Variable == "System") %>% 
  gather(Date, Hrs, -("railroad":"Sub-Variable"))

But I want to run the following code, adding a second option under variable:

dwell <- rail %>% 
  filter_(Measure == "Average Terminal Dwell Time (Excluding Cars on Run Through Trains) (Hours)",
         Variable == "System" & "System (U.S.)") %>% 
  gather(Date, Hrs, -("railroad":"Sub-Variable"))

But when I do this I get the folloing error: "operations are possible only for numeric, logical or complex types." I have tried swapping the & for | and that didn't work either. I feel like this is going to be a simple switch once someone tells me. Thanks!

matt_lnrd
  • 329
  • 1
  • 9
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data, all necessary code, and a clear explanation of what you're trying to do and what hasn't worked. – camille Jan 24 '20 at 23:13

2 Answers2

1

Try changing Variable == "System" & "System (U.S.)" for Variable == "System" | Variable == "System (U.S.)". That should work.

0

We can use %in% with Variable if we are trying on a fixed match for multiple elements i.e. > 1. With %in%, we can include any number of elements as a vector

library(dplyr)
library(tidyr)
rail %>% 
    filter_(Measure == "Average Terminal Dwell Time (Excluding Cars on Run Through Trains) (Hours)",
             Variable %in% c("System", "System (U.S.)")) %>% 
    gather(Date, Hrs, -("railroad":"Sub-Variable"))

Or may be more easier if it can be matched with regex

rail %>% 
    filter_(Measure == "Average Terminal Dwell Time (Excluding Cars on Run Through Trains) (Hours)",
         startsWith(Variable, "System")) %>% 
    gather(Date, Hrs, -("railroad":"Sub-Variable"))

In the OP's code Variable == "System" & "System (U.S.)" The & part is not evaluated as we need to either specify the 'Variable' twice, but that is still not correct because the column can't have two elements at the same position

akrun
  • 874,273
  • 37
  • 540
  • 662