【问题标题】:imap() not working as I expected, what am I missing?imap() 没有按我的预期工作,我错过了什么?
【发布时间】:2021-06-23 11:51:19
【问题描述】:

所以在这里,当我使用索引 (".y") 浏览列表时,我遇到了 imap 错误。下面我已经让它与 map2 一起工作,但这很令人困惑,因为我制作 map2() 函数的方式与我认为 imap 会做的方式完全相同。但显然不是,否则不会出错。

我很想尽可能地理解 purrr 的逻辑,谁能告诉我这是怎么回事?

library(purrr)

l1 <- list(a='a', b='b')



# single brackets -  'missing value where TRUE/FALSE needed'
imap(l1, ~{
  y1 <- names(l1)[.y]
  if(y1 == 'a') out1 <- TRUE
  if(y1 == 'b') out1 <- FALSE
  out
})
# double brackets -  subscript out of bounds
imap(l1, ~{
  y1 <- names(l1)[[.y]]
  if(y1 == 'a') out1 <- TRUE
  if(y1 == 'b') out1 <- FALSE
  out
})


# emulating what I think imap() does 
map2(l1, seq_along(l1), ~{
  y1 <- names(l1)[.y]
  if(y1 == 'a') out1 <- TRUE
  if(y1 == 'b') out1 <- FALSE
  out1
})

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    如果列表中存在名称,.y 是列表的名称,而不是索引。所以,

    names(l1)['a'] #returns
    #[1] NA
    

    这解释了'missing value where TRUE/FALSE needed'

    names(l1)[['a']]
    

    返回

    名称错误(l1)[["a"]] : 下标越界

    你需要的是-

    purrr::imap(l1, ~{
      if(.y == 'a') out1 <- TRUE
      if(.y == 'b') out1 <- FALSE
      out1
    })
    
    #$a
    #[1] TRUE
    
    #$b
    #[1] FALSE
    

    【讨论】:

      【解决方案2】:

      也许你只是需要

      imap(l1, ~ if(.y == 'a')  TRUE else FALSE)
      
      $a
      [1] TRUE
      
      $b
      [1] FALSE
      

      【讨论】:

      • 好吧,如果你真的想简化这个例子,imap(l1, ~ .y == 'a') 就足够了。
      • 在我的真实用户案例中,它要复杂得多,但谢谢
      猜你喜欢
      • 1970-01-01
      • 2019-11-09
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2019-08-28
      • 2014-10-18
      相关资源
      最近更新 更多