My previous question that I thought would extend to my problem wasn't specific enough so I am revisiting again:
My actual data frame has many more columns.
library(tidyverse)
# not installed in session but needed to reference:
# laeken::gini
df <- data.frame(a1 = c(1:5),
b1 = c(3,1,3,4,6),
c1 = c(10:14),
a2 = c(9:13),
b2 = c(3:7),
c2 = c(15:19))
> df
a1 b1 c1 a2 b2 c2
1 1 3 10 9 3 15
2 2 1 11 10 4 16
3 3 3 12 11 5 17
4 4 4 13 12 6 18
5 5 6 14 13 7 19
I would like add a column to df
using tidyverse
's mutate
that is the result of the output function my_gini
(shown below):
my_gini <- function(some_vector){
incs = c(1,2,5,9)
laeken::gini(inc = incs, weights = some_vector)
}
This function needs to take a vector that would be made up of multiple different column values from df
defined as my_cols
:
my_cols = c("b1","c1", "b2","c2")
I suspect I would need to use purrr
here something like:
df %>%
mutate(my_g = pmap_dbl(
select(., my_cols), ~ c(...) %>%
{my_gini(.[my_cols])}
))
which is supposed to add a column my_g
to the df
such that the first row would be:
my_gini(c(3,10, 3,15)) # 32.5564
and the second row would be:
my_gini(c(1,11,4,16)) # 29.66243
And so on.
However, it doesn't work. I get an error:
Error: Result 1 is not a length 1 atomic vector
Doing the same action with sum
works just fine so I am not sure why it's not working here.
df %>%
mutate(my_g = pmap_dbl(
select(., my_cols), ~ c(...) %>%
{sum(.[my_cols])}
))
Thank you in advance.