我有以下数据框(抱歉没有提供dput的示例,当我在此处粘贴时,它似乎不适用于列表):
现在,我想创建一个新列y是需要之间的区别mnt_ope,并ref_amount为每一个元素ref_amount.结果将是每行中具有与相应值相同的元素数量的列表ref_amount.
我试过了:
data <- data %>%
mutate( y = mnt_ope - ref_amount)
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误:
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"))
Run Code Online (Sandbox Code Playgroud)
小智 5
您不能使用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 附加回您的数据帧)。
希望有帮助!