【问题标题】:Dplyr : use mutate with columns that contain listsDplyr:对包含列表的列使用 mutate
【发布时间】:2018-12-20 13:53:19
【问题描述】:

我有以下数据框(很抱歉没有提供带有 dput 的示例,当我将其粘贴到列表时,它似乎不适用于列表):

现在我正在尝试为ref_amount 的每个元素创建一个新列y 来获取mnt_operef_amount 之间的差异。结果将是,在每一行中,一个列表的元素数量与ref_amount 的对应值相同。

我试过了:

data <- data %>%
   mutate( y = mnt_ope - ref_amount)

但我得到了错误:

Evaluation error: non-numeric argument to binary operator.

dput

structure(list(mnt_ope = c(500, 500, 771.07, 770.26, 770.26, 
770.26, 770.72, 770.72, 770.72, 770.72, 770.72, 779.95, 779.95, 
779.95, 779.95, 2502.34, 810.89, 810.89, 810.89, 810.89, 810.89
), ref_amount = list(c(500, 500), c(500, 500), c(771.07, 770.26, 
770.26), c(771.07, 770.26, 770.26), c(771.07, 770.26, 770.26), 
    c(771.07, 770.26, 770.26), c(771.07, 770.26, 770.26), c(771.07, 
    770.26, 770.26), c(771.07, 770.26, 770.26), c(771.07, 770.26, 
    770.26), c(771.07, 770.26, 770.26), c(771.07, 770.26, 770.26
    ), c(771.07, 770.26, 770.26), c(771.07, 770.26, 770.26), 
    c(771.07, 770.26, 770.26), 2502.34, c(810.89, 810.89, 810.89
    ), c(810.89, 810.89, 810.89), c(810.89, 810.89, 810.89), 
    c(810.89, 810.89, 810.89), c(810.89, 810.89, 810.89))), row.names = c(NA, 
-21L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

  • 请使用dput 显示数据集。是否为list
  • @jogo 抱歉,这是 ref_amount 不是 diff_amount @akrun 很抱歉,但我似乎无法使用 dput。它不会在文本编辑器中以正确的格式粘贴。是的,这是一个list 专栏。
  • 我猜你需要在mutate中使用类似purrr::map/purrr::pmap的东西。
  • @akrun 对不起,我的错,我做了必要的编辑。

标签: r dplyr


【解决方案1】:

您不能使用dplyr 以这种方式直接从列表列中减去。我发现完成您所引用的任务的最佳方法是使用purrr::map。以下是它的工作原理:

data <- data %>% mutate(y = map2(mnt_ope, ref_amount, function(x, y){ x - y }))

或者,更简洁:

data <- data %>% mutate(y = map2(mnt_ope, ref_amount, ~.x - .y))

map2 在这里将双输入函数应用于两个向量(在您的情况下,数据框的两列)并将结果作为向量返回(我们使用 mutate 将其附加回您的数据框)。

希望有帮助!

【讨论】:

  • 谢谢,确实很完美。现在我想这在sparklyr 中不起作用......不幸的是......我可能需要在去sparklyr 时扩展到几行
【解决方案2】:

对于每个元素都有效:需要添加一个循环:

例如第 5 个数据点 dt$mnt_ope[5]-unlist(dt$ref_amount[5]) 产量:

[1] -0.81  0.00  0.00

使用 while 循环遍历行数(比 purrr 简单)

i <-0
while(i < nrow(dt)){
  print(dt$mnt_ope[i]-unlist(dt$ref_amount[i]))
  i = i+1
  }

输出:

[1] 0 0
[1] 0 0
[1] 0.00 0.81 0.81
[1] -0.81  0.00  0.00
[1] -0.81  0.00  0.00
[1] -0.81  0.00  0.00
[1] -0.35  0.46  0.46
[1] -0.35  0.46  0.46
[1] -0.35  0.46  0.46
[1] -0.35  0.46  0.46
[1] -0.35  0.46  0.46
[1] 8.88 9.69 9.69
[1] 8.88 9.69 9.69
[1] 8.88 9.69 9.69
[1] 8.88 9.69 9.69
[1] 0
[1] 0 0 0
[1] 0 0 0
[1] 0 0 0
[1] 0 0 0

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2015-04-29
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多