Home > Net >  is there an analogue of the condition where in R
is there an analogue of the condition where in R

Time:03-28

I want to do a simple filter with these data:

Mydata=structure(list(V1 = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 259L, 260L, 261L, 262L, 263L, 264L, 265L, 266L, 267L), date = c("31.05.2021", 
"02.06.2021", "03.06.2021", "04.06.2021", "05.06.2021", "06.06.2021", 
"07.06.2021", "08.06.2021", "09.06.2021", "10.06.2021", "11.06.2021", 
"12.06.2021", "13.06.2021", "14.06.2021", "15.06.2021", "16.06.2021", 
"30.08.2021", "31.08.2021", "01.09.2021", "02.09.2021"), row = c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L), col = c(12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 
20L, 21L, 22L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L), 
    KF2_4 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-20L))

I’m trying to to filter to dates where date>"01.06.2021" and date<"30.08.2021". I tried to like this:

filter(mydata,date>"01.06.2021" & date<"30.08.2021")

but I get this error:

Error in date > "06/01/2021" :
   comparison (6) is only possible for elementary and list types

CodePudding user response:

Alternatively, one can use lubridate::dmy and dplyr::filter:

library(dplyr)
library(lubridate)

filter(Mydata, dmy(date) > dmy("01.06.2021") & dmy(date) < dmy("30.08.2021"))

#>     V1       date row col KF2_4
#> 1    1 02.06.2021   2  13     0
#> 2    2 03.06.2021   2  14     0
#> 3    3 04.06.2021   2  15     0
#> 4    4 05.06.2021   2  16     0
#> 5    5 06.06.2021   2  17     0
#> 6    6 07.06.2021   2  18     0
#> 7    7 08.06.2021   2  19     0
#> 8    8 09.06.2021   2  20     0
#> 9    9 10.06.2021   2  21     0
#> 10  10 11.06.2021   2  22     0
#> 11 259 12.06.2021   2  12     0
#> 12 260 13.06.2021   2  13     0
#> 13 261 14.06.2021   2  14     0
#> 14 262 15.06.2021   2  15     0
#> 15 263 16.06.2021   2  16     0

CodePudding user response:

The "date" column should be in date format, i.e. of class "Date", then it works. Easy using as.Date.

Mydata <- transform(Mydata, date=as.Date(date, '%d.%m.%Y'))

subset(Mydata, date > "2021-06-01" & date < "2021-08-30")
#     V1       date row col KF2_4
# 2    1 2021-06-02   2  13     0
# 3    2 2021-06-03   2  14     0
# 4    3 2021-06-04   2  15     0
# 5    4 2021-06-05   2  16     0
# 6    5 2021-06-06   2  17     0
# 7    6 2021-06-07   2  18     0
# 8    7 2021-06-08   2  19     0
# 9    8 2021-06-09   2  20     0
# 10   9 2021-06-10   2  21     0
# 11  10 2021-06-11   2  22     0
# 12 259 2021-06-12   2  12     0
# 13 260 2021-06-13   2  13     0
# 14 261 2021-06-14   2  14     0
# 15 262 2021-06-15   2  15     0
# 16 263 2021-06-16   2  16     0
  • Related