Comparing Each Element of Two Lists in R -
i have dataset in r following structure:
data <- structure(list(cust_id = c("003", "023", "023", "023", "023", "041", "056", "056"), record_date = list(structure(16130, class = "date"), structure(c(16130, 16130, 16130, 16130), class = "date"), structure(c(16150, 16150, 16150, 16150), class = "date"), structure(c(16161, 16161, 16161, 16161), class = "date"), structure(c(16162, 16162, 16162, 16162), class = "date"), structure(16133, class = "date"), structure(c(16088, 16088 ), class = "date"), structure(c(16095, 16095), class = "date")), compare_date = list(structure(16130, class = "date"), structure(c(16130, 16150, 16161, 16162), class = "date"), structure(c(16130, 16150, 16161, 16162), class = "date"), structure(c(16130, 16150, 16161, 16162), class = "date"), structure(c(16130, 16150, 16161, 16162), class = "date"), structure(16133, class = "date"), structure(c(16088, 16095), class = "date"), structure(c(16088, 16095), class = "date"))), row.names = c(na, -8l), class = "data.frame", .names = c("cust_id", "record_date", "compare_date")) cust_id record_date compare_date 1 003 16130 16130 2 023 16130, 16130, 16130, 16130 16130, 16150, 16161, 16162 3 023 16150, 16150, 16150, 16150 16130, 16150, 16161, 16162 4 023 16161, 16161, 16161, 16161 16130, 16150, 16161, 16162 5 023 16162, 16162, 16162, 16162 16130, 16150, 16161, 16162 6 041 16133 16133 7 056 16088, 16088 16088, 16095 8 056 16095, 16095 16088, 16095 i compare each element of "record_date" , each element of "compare_date." want result equal amount of times "compare_date" within 14 days after "record_date." know how compare 2 vectors, comparing 2 lists seems giving me trouble. have tried using lapply or sapply, can loop through 1 list @ time.
does have easy solution problem? expect expected output following:
within14 1: 0 2: 2 3: 1 4: 0 5: 1 6: 0 7: 0 8: 0
perhaps, looking mapply. can edit fun argument of mapply want on each rd , cd argument.
mapply passes 1 element each of data$record_date , data$compare_date rd , cd arguments of fun respectively.
mapply(fun = function(rd, cd) { d <- as.numeric(cd - rd) sum(d > 0 & d < 15) }, rd = data$record_date, cd = data$compare_date) ## [1] 0 0 2 1 0 0 1 0
Comments
Post a Comment