gibbz00 gibbz00 - 1 month ago 20
R Question

lapply with two column arguments

These is my dataframes

library(data.table)
df <- fread('
Account Date NextDate
A 2016-01-01 2016-02-01
A 2016-02-01 2016-11-05
B 2016-03-10 2016-11-05')


ab <- fread('
Date Amount
2015-06-01 55
2016-01-31 55
2016-02-28 65
2016-03-31 75')


I want to create a list by doing a loop as of each row in
df
and pick all rows from
ab
where
ab$Date
is greater than
df$Date
and less than
df$NextDate
so that the output looks like this:

[[1]]

Date Amount
2016-01-31 55

[[2]]

Date Amount
2016-02-28 65
2016-03-31 75

[[3]]
Date Amount
2016-03-31 75


This is my attempt:

list<- lapply(df$Date, function(x,y) br[Date > x & Date < y ],y=df$NextDate)

Answer

Create a vector that checks whether rows of ab meet your conditions, then use it to select rows of ab.

lapply(1:nrow(df), function(x) {
  ab[which(ab$Date > df[x, get("Date")] & ab$Date < df[x, get("NextDate")]), ]
})