I am still new to R, and I'm running into an issue. I have a file with Raw Data :
dfRawData <-
  data.table(
    "Model" = c(
      "Car1",
      "Car1",
      "Car1",
      "Car2",
      "Car2",
      "Car2",
      "Car3",
      "Car3",
      "Car3"
    ),
    "variable" = c(
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3",
      "Metric1",
      "Metric2",
      "Metric3"
    ),
    "valeur" = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
  )
I want to subset this data table based on the name of the car, and the metric. However, I'd like to avoid using if statements, because my code is already very long. To what I've understood, case_when could be very useful. I know that the formula for the subsetted data table is right, since when I use if statement, it returns me what I want. Yet, when I use case_when, I get the following error :
Error in `[.data.frame`(x, i) : undefined columns selected
Does someone know what I'm doing wrong ? Here is my code :
carName = 'Car1' ##Can be changed
dfCarMetric = case_when(
           carName == 'Car1' ~ dfRawData[which(dfRawData[["Model"]] == carName  &
                                               dfRawData[["variable"]] %in% c("Metric1", "Metric2")), ],
           carName == 'Car2' ~ dfRawData[which(dfRawData[["Model"]] %in% c("Car2", "Car3")  &
                                               dfRawData[["variable"]] == "Metric1"), ]
       )
I want to have this in the end :
carName = 'Car1'
    dfCarMetric
       Model variable valeur
    1:  Car1  Metric1      1
    2:  Car1  Metric2      2
carName = 'Car2'
    dfCarMetric
      Model variable valeur
    4  Car2  Metric1      4
    7  Car3  Metric1      7
Thank you very much for your answers !!
 
    