Reputation: 1987
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)
Upvotes: 3
Views: 1056
Reputation: 4282
You can use apply:
apply(df, 1, function(x) ab[ab$Date>x[2] & ab$Date<x[3],])
Upvotes: 3
Reputation: 263342
It's possible this is not truly in the dataframe traditions, but I think the logic is fairly clear if you are coming from a base-R background. The data.table "[" function needs to have unquoted column names in a list to delive just column values:
apply( df[, list(Date,NextDate)] , 1,
function(dts) ab[ ab$Date > dts['Date'] & ab$Date < dts['NextDate'], ])
[[1]]
Date Amount
1: 2016-01-31 55
[[2]]
Date Amount
1: 2016-02-28 65
2: 2016-03-31 75
[[3]]
Date Amount
1: 2016-03-31 75
Upvotes: 2
Reputation: 4206
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")]), ]
})
Upvotes: 1