Home > Software design >  specifying row position in subset function (R)
specifying row position in subset function (R)

Time:09-29

I have the following vector with dates in R

Dates <- structure(list(Date = structure(c(18109, 18140, 18170, 18201, 
18231, 18262, 18293, 18322, 18353, 18383, 18414, 18444, 18475, 
18506, 18536, 18567, 18597, 18628, 18659, 18687, 18718, 18748, 
18779, 18809, 18840, 18871, 18901, 18932, 18962, 18993, 19024
), class = "Date")), row.names = c(NA, -31L), class = c("tbl_df", 
"tbl", "data.frame"))

If I wanted to subset the last two dates in this vector, I could this.

subset(Dates, Date >= as.Date('2022-01-01'))

Is there a way to specify the row position that I want in the subset function as opposed to writing out the date '2022-01-01'? I've tried subset(Dates, Date >= 30) but that didn't work

CodePudding user response:

The lhs should be on the same class i.e. instead of using the >= on the Date, build the logic around the sequence of 'Date'

subset(Dates, seq_along(Date) >=30)

-output

# A tibble: 2 × 1
  Date      
  <date>    
1 2022-01-01
2 2022-02-01
  • Related