Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 337
gibbz00 Avatar asked Feb 16 '26 15:02

gibbz00


1 Answers

You can use apply:

apply(df, 1, function(x) ab[ab$Date>x[2] & ab$Date<x[3],])
like image 125
Marcelo Avatar answered Feb 19 '26 05:02

Marcelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!