imap() 没有像我预期的那样工作,我错过了什么?

imap() not working as I expected, what am I missing?

因此,当我使用索引 (".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
})

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

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

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

names(l1)[['a']]

returns

Error in names(l1)[["a"]] : subscript out of bounds

你需要的是-

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

#$a
#[1] TRUE

#$b
#[1] FALSE

也许你只是需要

imap(l1, ~ if(.y == 'a')  TRUE else FALSE)

$a
[1] TRUE

$b
[1] FALSE