Home > front end >  How to set function arguments from data frame using purrr::pmap without writing all col names?
How to set function arguments from data frame using purrr::pmap without writing all col names?

Time:09-30

I have this data frame and function.

df <- tibble(
  a = "a",
  b = "b",
  c = "c",
  d = "d",
  e = "e",
  f = "f",
  g = "g"
)

pmap(df, function(a, b, c, d, e, f, g) {
    
    var_1 <- paste0(a, b)

    var_2 <- c   d   e

    var_3 <- f/g

   tibble(
   a = var_1
   b = var_2
   c = var_3
)
    
  })

The function works as expected. Since the col names could be more than seven I don't want to have to write all col names inside function(). What could be done?

Desired similar code:

pmap(df, function(names(df)) {
  
    var_1 <- paste0(a, b)

    var_2 <- c   d   e

    var_3 <- f/g

   tibble(
   a = var_1
   b = var_2
   c = var_3
)
  
})

CodePudding user response:

In this situation, I prefer with(list(...), #stuff here ).

Building on stefan's working solution:

pmap(df,~with(list(...),{var_1 <- paste0(a, b);
                        var_2 <- c   d   e;
                        var_3 <- f/g;
                        tibble(a = var_1, b = var_2, c = var_3)}))
#[[1]]
## A tibble: 1 × 3
#  a         b     c
#  <chr> <dbl> <dbl>
#1 ab        6   0.8

CodePudding user response:

Using ..., list2env and rlang::current_env you could do:

Note: I slightly changed your example data so that c to g are numerics.

library(purrr)
library(tibble)
library(rlang)

df <- tibble(
  a = "a",
  b = "b",
  c = 1,
  d = 2,
  e = 3,
  f = 4,
  g = 5
)

pmap(df, function(...) {
  list2env(list(...), envir = rlang::current_env())
  
  var_1 <- paste0(a, b)
  
  var_2 <- c   d   e
  
  var_3 <- f/g
  
  tibble(
    a = var_1,
    b = var_2,
    c = var_3
  )
})
#> [[1]]
#> # A tibble: 1 × 3
#>   a         b     c
#>   <chr> <dbl> <dbl>
#> 1 ab        6   0.8
  • Related