Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying pmap list arguments to a function nested within another function

Tags:

r

purrr

pmap

I need to perform some rowwise operations with the help of pmap variants but I can't do so when it comes to passing the list of arguments (that is the ".l" argument) to a function that's nested within another function.

I've tried various things including passing the name of the arguments and the dot dot dot syntax all to no avail. I need to know if there's a way to do this as I need to extend this to more complicated functions.

Let's say I have the following data frame and that I would like to paste the first two columns from each row. I can easily do that with the following code:

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

However, if I would like to expand this so that I can lower case the first two letters prior to merging them, my attempt fails. I would like to see if I can get 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
like image 467
Diego Avatar asked Mar 26 '26 23:03

Diego


1 Answers

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)

like image 120
akrun Avatar answered Mar 28 '26 17:03

akrun