I am trying to functionalize my R code, but have run into problems because a lot of my work involves the use of shifted vectors in data.table and pmap_dfr simply does not implement data.table's shift inside the function as expected. I am using R 4.2.2 on a MacOS Venture 13.1 anad the same issue appears in Windows 11. I have presented a minimal working example below.
library(data.table)
library(tidytable)
minimal_failing_function <- function(A){
DT <- data.table(A)
DT[ , A:= shift(A, fill = NA, type = "lag", n = 1)] %>% `[`
return(DT)
}
# works
minimal_failing_function(c(1,2))
# fails
tidytable::pmap_dfr(.l = list(c(1,2)),
.f = minimal_failing_function)
The line tidytable::pmap_dfr
should return:
A
1: NA
2: 1
Instead, I get:
# A tidytable: 2 × 1
A
<dbl>
1 NA
2 NA
I am looking for really any solution that will enable me access to pmap
functionality.
On the suggestion of stefan, I realized that pmap_dfr wants a list of lists for its input. It automatically unlists the interior list as a vector.
tidytable::pmap_dfr(.l = list(A = list(c(1,2))), .f = minimal_failing_function)
gives the desired result.