首页 > 解决方案 > 为什么keep from purrr在map中返回NULL?

问题描述

我需要比较嵌套tibbles 中的字符串。这是我的数据的样子:

library(tidyverse)

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

我需要返回上个月没有出现在当月的那个字符串。

我使用此代码来执行此操作。

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))
  }))

output$Lost即使该行包含零

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

工作正常并返回 1。

标签: rpurrr

解决方案


map用inside 替换会产生正确map2mutate输出。


推荐阅读