首页 > 解决方案 > 将列添加到数据框中,该数据框是采用多列(逐行)作为输入向量的函数的结果

问题描述

我之前认为会扩展到我的问题的问题不够具体,所以我再次重新审视:

我的实际数据框有更多列。

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

我想在dfusing tidyverse'smutate中添加一列,它是输出函数的结果my_gini(如下所示):

my_gini <- function(some_vector){
  incs = c(1,2,5,9)
  laeken::gini(inc = incs, weights = some_vector)
}

此函数需要一个向量,该向量由df定义为的多个不同列值组成my_cols

my_cols = c("b1","c1", "b2","c2")

我怀疑我需要在purrr这里使用类似的东西:

df %>% 
  mutate(my_g = pmap_dbl(
    select(., my_cols), ~ c(...) %>% 
      {my_gini(.[my_cols])}
    ))

这应该向第一行添加一my_gdf

my_gini(c(3,10, 3,15)) # 32.5564

第二行是:

my_gini(c(1,11,4,16))  # 29.66243

等等。

但是,它不起作用。我收到一个错误:

Error: Result 1 is not a length 1 atomic vector

做同样的动作sum效果很好,所以我不确定为什么它在这里不起作用。

df %>% 
  mutate(my_g = pmap_dbl(
    select(., my_cols), ~ c(...) %>% 
      {sum(.[my_cols])}
    ))

先感谢您。

标签: rpurrr

解决方案


尝试只使用pmapVice pmap_dbl

df %>% 
  mutate(my_g = unlist(pmap(
    select(., my_cols), ~ c(...) %>% 
      {my_gini(.[my_cols])}
    )))

  a1 b1 c1 a2 b2 c2     my_g
1  1  3 10  9  3 15  32.5564
2  2  1 11 10  4 16 29.66243
3  3  3 12 11  5 17 32.32696
4  4  4 13 12  6 18 33.26741
5  5  6 14 13  7 19  34.8913

pmap_dbl期待数字输入,但您的函数创建了 S3 类 gini/indicator 的对象。当我运行它时,pmap_dbl我收到以下警告:

Error: Evaluation error: Result 1 must be a single double, not a vector of class `gini/indicator` and of length 10

所以这涉及到 R 的一些更高级的计算机编程元素,但基本上你的函数创建了一种类型的对象,它不是基础 R 的原生对象,并且不会总是像你发现的那样与其他函数/包一起玩得很好.

因此,要了解更多细节以及为什么不能将其强制转换为数字,您需要查看函数实际创建的内容。当您强制转换为字符串时,您会得到以下结果:

1  list(value = 32.556404997203, valueByStratum = NULL, varMethod = NULL, var = NULL, varByStratum = NULL, ci = NULL, ciByStratum = NULL, alpha = NULL, years = NULL, strata = NULL)
2 list(value = 29.6624331550802, valueByStratum = NULL, varMethod = NULL, var = NULL, varByStratum = NULL, ci = NULL, ciByStratum = NULL, alpha = NULL, years = NULL, strata = NULL)
3 list(value = 32.3269611074489, valueByStratum = NULL, varMethod = NULL, var = NULL, varByStratum = NULL, ci = NULL, ciByStratum = NULL, alpha = NULL, years = NULL, strata = NULL)
4 list(value = 33.2674137552186, valueByStratum = NULL, varMethod = NULL, var = NULL, varByStratum = NULL, ci = NULL, ciByStratum = NULL, alpha = NULL, years = NULL, strata = NULL)
5 list(value = 34.8913043478261, valueByStratum = NULL, varMethod = NULL, var = NULL, varByStratum = NULL, ci = NULL, ciByStratum = NULL, alpha = NULL, years = NULL, strata = NULL)```

推荐阅读