1
votes

The following piece of code works as expected:

library(tidyverse)
tib <- tibble(x = c(1,2), y = c(2,4), z = c(3,6)) 
tib %>% pmap(c)
#[[1]]
#x y z
#1 2 3
#
#[[2]]
#x y z
#2 4 6

But if I define the function

my_c_1 <- function(u, v, w) c(u, v, w)

I get an error:

tib %>% pmap(my_c_1)
#Error in .f(x = .l[[c(1L, i)]], y = .l[[c(2L, i)]], z = .l[[c(3L, i)]],  :
#  unused arguments (x = .l[[c(1, i)]], y = .l[[c(2, i)]], z = .l[[c(3, i)]])

Equivalently, for a named list with the base vector function all works well:

lili_1 <- list(x = list(1,2), y = list(2,4), z = list(3,6))
pmap(lili_1, c)
#[[1]]
#x y z
#1 2 3
#
#[[2]]
#x y z
#2 4 6

And with the user-defined function I get the same error:

pmap(lili_1, my_c_1)
#Error in .f(x = .l[[c(1L, i)]], y = .l[[c(2L, i)]], z = .l[[c(3L, i)]],  :
#unused arguments (x = .l[[c(1, i)]], y = .l[[c(2, i)]], z = .l[[c(3, i)]])

However, for an un-named list with the user-defined function, it works:

lili_2 <- list(list(1,2), list(2,4), list(3,6))
pmap(lili_2, my_c_1)
#[[1]]
#[1] 1 2 3
#
#[[2]]
#[1] 2 4 6

I don't quite understand why things break with named lists and user-defined functions. Any insight?

BTW, I found a temporary workaround by defining:

my_c_2 <- function(...) c(...)

Then all works well, even with named lists... which leaves me even more puzzled.
This is in the spirit of a minimal reproducible example. In my current working code I would like to be able to pipe tibbles to pmap with my more general defined function without using the ... workaround for my variables.

1
Forgot to mention I am using R version 3.4.1 with purrr_0.2.3 (on macOS Sierra 10.12.6).Habert

1 Answers

3
votes

your function my_c_1 has arguments u, v, w but you pass a list with names x, y, z. If you don't want a function with no named arguments (..., such as base's c), you should make sure the names match in your call.