I am quite a newbie in R
and therefore cannot explain the following behavior.
So, let's assume I have the this data
structure.
> use_data
ID value1 value2 value3 Time
<int> <list> <list> <list> <dttm>
1 52 <tibble [96 x 25]> <tibble [59 x 26]> <NULL> 2012-04-25 03:00:00
2 24 <NULL> <tibble [30 x 26]> <NULL> 2012-07-18 13:45:00
For simplicity, the following example is not very expressive, but it serves as a demonstration of the problem. That is, I want to use the pmap
function to iterate over the columns in parallel. At the moment I only return the ID
to create the new column target
:
fun_example <- function(df) {
result_df <- df %>% mutate(target = purrr::pmap(
.l = list(ID, value1, value2),
.f = function(x, y, z){
return (x)
}
)) %>% unnest(target)
}
(fun_example(use_data))
As intended, this results in
ID value1 value2 value3 Time target
<int> <list> <list> <list> <dttm> <int>
1 52 <tibble [96 x 25]> <tibble [59 x 26]> <NULL> 2012-04-25 03:00:00 52
2 24 <NULL> <tibble [30 x 26]> <NULL> 2012-07-18 13:45:00 24
Now I want to set the list with data to iterate over in advance by defining cols <-list(df$ID, df$value1, df$value2)
and then
fun_example <- function(df) {
result_df <- df %>% mutate(target = purrr::pmap(
.l = cols,
.f = function(x, y, z){
return (x)
}
)) %>% unnest(target)
}
(fun_example(use_data))
However, this gives me the following error:
Problem while computing `target = purrr::pmap(...)`.
x `target` must be size 1, not 2.
i The error occurred in group 1: ID = 24.
I guess the problem is that pmap
somehow no longer gives the desired result. Finally, two questions:
- Can someone explain what is happening in the example described?
- Besides defining the data to iterate over directly, is there a way to pass strings of the column like cols <- list("ID", "value1", "value2") ?
pmap
takes lists, while withinmutate
we pass bare names (mpg not "mpg").So given a string vector, we parse it using
parse_exprs
and then create use list and!!!
operator to unquote and evaluate these expressions.