0

I need to compare strings within nested tibbles. This is how my data looks:

library(tidyverse)

mydata = data.frame(
  Months = c(1 ,1 ,1 , 2, 2, 2),
  Strings = rep(c('1', '2', '3', '1', '3', '4'))
)

I need to return that one string from the previous month that did not appear in the current month.

I use this code to do so.

output = mydata %>%
  nest(Nested = -Months) %>%
  arrange(Months) %>%
  mutate(Lost= map(Nested, lag(Nested), .f = function(.CurrentMonth, .PreviousMonth){
    length(keep(.PreviousMonth$Strings ,!.PreviousMonth$Strings %in% .CurrentMonth$Strings))
  }))

But output$Lost contains zeros even though the line

length(keep(output$Nested[[1]]$Strings, !output$Nested[[1]]$Strings %in% output$Nested[[2]]$Strings ))

works fine and returns 1.

1 Answers1

1

Replacing map with map2 within mutate results in the correct output.