I am trying to use case_when
to call different functions inside map
on list-columns depending on the condition. For example, say I have two list-columns, the first element in each of the lists contains a vector of numbers, and the second contains a vector of characters.
test.df <- tibble(
has_numbers = c(TRUE, FALSE),
a = list(1:3, "foo"),
b = list(4:6, "bar")
)
> test.df
# A tibble: 2 x 3
has_numbers a b
<lgl> <list> <list>
1 TRUE <int [3]> <int [3]>
2 FALSE <chr [1]> <chr [1]>
I want to create a new list-column where if the row contains numbers it adds them up, otherwise it pastes the strings together. I would approach this problem by using a case_when
inside mutate
, and mapping the relevant function over the list columns based on the result of case_when
.
test.df %>%
mutate(result = case_when(
has_numbers ~ map2(a, b, sum),
!has_numbers ~ map2(a, b, paste)
))
However, it looks like the call to sum
is being attempted whether or not the case_when
evaluates to TRUE
, as it returns this error:
Error: Problem with `mutate()` column `result`.
i `result = case_when(...)`.
x invalid 'type' (character) of argument
This error is the same error you would get when trying to add two characters, so I know that the map2
call with add
is being attempted for each row of the data regardless of what case_when
evaluates to.
> sum("foo", "bar")
Error in sum("foo", "bar") : invalid 'type' (character) of argument
Any help/ideas are appreciated, thanks!