将 pmap 列表参数应用于嵌套在另一个函数中的函数

Applying pmap list arguments to a function nested within another function

我需要在 pmap 变体的帮助下执行一些按行操作,但在将参数列表(即“.l”参数)传递给嵌套在另一个函数中的函数。

我尝试了各种方法,包括传递参数名称和点点语法,但都无济于事。我需要知道是否有办法做到这一点,因为我需要将其扩展到更复杂的功能。

假设我有以下数据框,我想粘贴每一行的前两列。我可以使用以下代码轻松做到这一点:

dff <- data_frame(
  first  = c("A", "B"),
  second = c("X", "Y"),
  third  = c("L", "M")
)

df_easy <- dff %>% 
  mutate(joined_upper = pmap_chr(list(first, second), function(...) paste(..., sep = "&")))

df_easy
#> # A tibble: 2 x 4
#>   first second third joined_upper
#>   <chr> <chr>  <chr> <chr>       
#> 1 A     X      L     A&X         
#> 2 B     Y      M     B&Y

但是,如果我想扩展它以便在合并它们之前将前两个字母小写,我的尝试失败了。我想看看能不能拿到dff3.

# df_hard <- dff %>% 
#   mutate(joined_smaller = pmap_chr(list(first, second), function(...) paste(tolower(...), sep = "&")))

dff3 <- data.frame(
  first  = c("A", "B"),
  second = c("X", "Y"),
  third  = c("L", "M"),
  joined_smaller = c("a&X", "b&Y")
)

dff3
#>   first second third joined_smaller
#> 1     A      X     L            a&X
#> 2     B      Y     M            b&Y

这是一种选择。请注意 pastestr_c 是向量化的,即

library(dplyr)
library(stringr)
dff %>% 
     mutate(joined_sma = str_c(tolower(first), second, sep="&"))

并假设这是一个仅针对 pmap

的练习
library(purrr)    
dff %>%
   mutate(joined_sma = pmap_chr(list(first, second), ~ c(...) %>% 
                {str_c(tolower(first(.)), .[-1], sep="&")}
      ))
# A tibble: 2 x 4
# first second third joined_sma
#  <chr> <chr>  <chr> <chr>     
#1 A     X      L     a&X       
#2 B     Y      M     b&Y       

此外,由于只有两列,我们可以使用约定 .x.y 来调用那些

dff %>%
   mutate(joined_sma = pmap_chr(list(first, second), ~     
       str_c(tolower(.x), .y, sep="&")
  ))

注意:在这里,我们使用 str_c 而不是 paste,因为当存在缺失值 (NA)

时,这可能会有不同的行为