purrr:::map 中元素的命名

问题描述 投票:0回答:1

在这个问题中在 tibble 上命名 pmap 的输出,我询问如何正确命名

pmap
调用的输出并得到了一个很好的答案,我认为我理解了。

当我进一步研究这种行为时,我不再确定我是否理解其内在原理:

library(purrr)
library(tibble)
params <- tibble(nm = LETTERS[1:2], x = 1:2, y = 2:3, z = 1:2)

## 1. setting names on the first argument gives the expected results
params %>%
  mutate(nm = set_names(nm)) %>% 
  pmap(function(nm, x, y, ...) {
    x + y
  }) %>%
  names()
# [1] "A" "B"


## 2. actually it does not need to be the first element
params %>%
  mutate(nm = set_names(nm)) %>% 
  pmap(function(x, y, nm, ...) {
    x + y
  }) %>%
  names()
# [1] "A" "B"

## 3. however, setting names on `x` does not work
params %>%
  mutate(x = set_names(x, nm)) %>% 
  pmap(function(x, y, nm, ...) {
    x + y
  }) %>%
  names()
# NULL

## 4. I thought maybe because they disappear during the addition `+`, but nope
params %>%
  mutate(z = set_names(z, nm)) %>% 
  pmap(function(x, y, nm, ...) {
    x + y
  }) %>%
  names()
# NULL

## 5. Ok maybe a catch all argument `...` prohibits this behaviour, but no
params %>%
  mutate(z = set_names(z, nm)) %>% 
  pmap(function(x, y, nm, z) {
    x + y
  }) %>%
  names()
# NULL

## 6. It seems that names on a character vector work even if not referenced directly
params %>%
  mutate(nm = set_names(nm)) %>% 
  pmap(function(x, y, ...) {
    x + y
  }) %>%
  names()
# [1] "A" "B"

有人可以告诉我这些名字最终是如何在

[p]map
通话中确定的吗?

r tidyverse purrr names
1个回答
1
投票

答案取自我对原始问题的评论。

名称取自小标题的第一列(这是向量列表)并应用于结果列表(调用函数)。

所以它几乎与函数本身如何计算结果无关。

步骤是

  1. 从 tibble/data.frame 的第一列中提取名称(对于
    pmap
    ),否则从
    x
  2. 中提取名称
  3. 将函数应用于元素并收集结果
  4. 使用步骤 1 中提取的名称命名结果元素
© www.soinside.com 2019 - 2024. All rights reserved.