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

r - Dplyr : use mutate with columns that contain lists-LMLPHP

现在,我正在尝试创建一个新列y,该列将mnt_ope的每个元素的ref_amountref_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"))

最佳答案

您不能使用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将其追加回您的数据帧)。

希望对您有所帮助!

关于r - Dplyr : use mutate with columns that contain lists,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51156614/

10-12 19:10