R: Accessing first three elements of splitted dataframe

Viewed 30

For example,

dateIntervals <- as.Date(c("2020-08-10", "2020-11-11", "2021-07-05"))
possibleDates <- seq(as.Date("2020-01-02"), dateIntervals[3], by = "day")

genDF<-function() data.frame(Date = sample(possibleDates, 100), Value = runif(100))
listdf <-replicate(2, genDF(), simplify = FALSE)

Yes, listdf has two dataframe elements(each 100 random dates in possibleDates and values) and listdf[[1]] is like this

A data.frame: 100 × 2
Date    Value
<date>  <dbl>
2020-07-24  0.63482411
2020-02-26  0.25989280
2020-10-26  0.21721077
2020-10-11  0.34774192
2020-08-18  0.67758312
2020-02-03  0.22929624
2020-06-10  0.30279353
2020-05-29  0.95549488
...
lapply(listdf, function(x) split(x, findInterval(x$Date, dateIntervals)))

Made listdf as a 2*3 list, splitted by date.

1.$`0`
A data.frame: 43 × 2
Date    Value
<date>  <dbl>
1   2020-07-24  0.63482411
2   2020-02-26  0.25989280
6   2020-02-03  0.22929624
7   2020-06-10  0.30279353
...
$`1`
A data.frame: 15 × 2
Date    Value
<date>  <dbl>
3   2020-10-26  0.21721077
4   2020-10-11  0.34774192
5   2020-08-18  0.67758312
31  2020-11-09  0.59149301
...
$`2`
A data.frame: 42 × 2
Date    Value
<date>  <dbl>
9   2021-06-28  0.10055644
10  2021-05-17  0.63942936
12  2021-04-22  0.63589801
13  2021-02-01  0.70106156
...

2.$`0`
A data.frame: 43 × 2
Date    Value
<date>  <dbl>
2   2020-07-16  0.81376364
4   2020-07-03  0.05152627
7   2020-01-21  0.98677433
8   2020-03-23  0.13513921
...

$`1`
A data.frame: 18 × 2
Date    Value
<date>  <dbl>
5   2020-11-01  0.02740125
12  2020-09-04  0.82042568
15  2020-08-12  0.54190868
16  2020-09-19  0.05933666
18  2020-10-05  0.04983061
...

$`2`
A data.frame: 38 × 2
Date    Value
<date>  <dbl>
1   2021-04-13  0.46199245
3   2021-06-12  0.71461155
6   2021-01-24  0.56527997
9   2021-04-17  0.72634151
13  2021-04-20  0.55489499
...

I want only first two of the splitted ones.($'0' and $'1' for 1. and 2.)

is there any parameter in the split function which does things like this? (getting only first or last n elements) I want something like this...

lapply(listdf, function(x) split(x, findInterval(x$Date, dateIntervals), some parameter=2))

yes this "2". Getting only the first two ones. is there a function parameter in split which can do this?

0 Answers
Related