Search code examples
rvectorusingsubset

dataframe subsetting using vector


I have a Data Frame

head(readDF1)

          Date sulfate nitrate   ID
279 2003-10-06    7.21   0.651    1
285 2003-10-12    5.99   0.428   10
291 2003-10-18    4.68   1.040  100
297 2003-10-24    3.47   0.363  200
303 2003-10-30    2.42   0.507  300
315 2003-11-11    1.43   0.474  332

If I'm subsetting using the below code it is working correct

readDF1[readDF1$ID==331]

but If I'm using

readDF1[readDF1$ID==1:300]

this is not working, I want to subset a Dataframe wihch has the values of the column ID from 1 to 300 (Asssume that ID contains values from 1 to 1000 and they are multiple)


Solution

  • == is the wrong operator here. You aren't asking 'which ID is equal to the sequence 1:331'. You want %in% (i.e. which ID values can be found in 1:331

    readDF1$ID[readDF1$ID %in% 1:331]