【问题标题】:How to pipe a dataset into a pmap?如何将数据集通过管道传输到 pmap?
【发布时间】:2020-09-09 10:42:42
【问题描述】:

我的 tibble 看起来像这样:

  dataset <- tibble(country = sample(c(11,23,18,17,12,19,30,16,14,13,15),7679,replace = T),yrbirth = floor(runif(7679,1900,1970)))

我有两个帮助向量来检查条件

country_code <- c(11,23,18,17,12,19,30,16,14,13,15)

crit_year <- c(1947,1969,1957,1953,1948,1958,1958,1949,1959,1947,1947)    

我有一个函数来做突变

f_g_treat <- function(dataset, country_code, crit_year){
  dataset_new <- dataset %>%
    filter(country == country_code) %>%
    mutate(treatment = ifelse(yrbirth >=crit_year-7,'Treat','Contr'))
  return(dataset_new$treatment)
}

现在我想将数据集通过管道传输到 pmap 中,但似乎这会引发错误。我的想法是这样的

dataset <- dataset %>%
 mutate(treatment =
 pmap(list(country_code, crit_year), ~f_g_treat(dataset = ., country_code = ..1, crit_year = ..2 )) %>%
           unlist() )

这样做会引发以下错误:

错误:mutate() 输入 treatment 有问题。 x 没有适用于 'filter_' 的方法应用于类“c('double', 'numeric')”的对象 i 输入 treatment 是 ``%>%(...)

当我尝试时:

dataset <- mutate(dataset, treatment =
                pmap(list(country_code, crit_year), ~f_g_treat(dataset = dataset, country_code = ..1, crit_year = ..2 )) %>%
                unlist() )

一切正常,我得到了预期的向量。所以我相信我在这部分使用了传递. 错误的匿名对象。有人可以帮我吗?

【问题讨论】:

  • 您的预期输出是什么?您想将整个数据集传递给f_g_treat 的每次调用吗?根据你的工作正常的例子,不在我的机器上运行。
  • 所以我的预期输出应该是第三列称为处理的数据集。哪个应该等于 pmap(...) %>% unlist 生成的向量 是的,我需要在 eacht 迭代中使用数据,因为我需要在变异之前先过滤一些参数。
  • @Bas 发现 MWE 的问题。现在它应该在你身边工作。此外,OP中的问题仍然存在。

标签: r dplyr purrr


【解决方案1】:

对于您的具体问题,do 可以解决您的问题:

do(dataset, mutate(., treatment =
                    pmap(list(country_code, crit_year), function(x, y) f_g_treat(dataset = ., country_code = x, crit_year = y )) %>%
                    unlist() )   )      

请注意,我必须使 pmap 中的函数参数显式(xy)以避免覆盖 do 创建的 .

我认为输出不正确,在您的工作示例中也不正确。 treatment列的粘贴顺序错误(即country_code, crit_year的顺序),而不是原始数据框中的顺序。

更好的方法是通过连接:

country_crit_year <- tibble(country = country_code, crit_year = crit_year)
dataset %>% 
  left_join(country_crit_year, by = "country") %>% 
  mutate(treatment = if_else(yrbirth >= crit_year-7, "Treat", "Contr"))

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    dataset %>%
      mutate(treatment = pmap(list(country_code, crit_year), 
                              f_g_treat, 
                              dataset = .) %>% unlist())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多