3

我需要在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
4

1 回答 1

2

Here is one option. Note that paste and str_c are vectorized i.e.

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

and assuming that this is an exercise just for 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       

Also, as there are only two columns, we can use convention .x, .y to call those

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

NOTE: Here, we are using str_c instead of paste as this can have different behavior when there is missing values (NA)

于 2019-09-05T18:32:26.923 回答