让我们假设以下向量:
prices <- c(10, 15, 20, 30)
和以下数据帧:
df <- data.frame(count = c(1, 3, 2, 4))
我想做的是,根据df
中的count
值,从价格向量中提取1:count
个值,并在我的数据框中求和.
所以我想我可以做:
library(tidyverse)
df |>
mutate(sum = sum(!!prices[1:count]))
但是,这会给出一个错误:
Error in quos(..., .ignore_empty = "all") :
object 'count' not found
我猜这是因为它查看外部向量,然后在全局环境中搜索count
,然而,它只存在于df中.
所以问题是,我如何将这个外部向量输入到我的数据框中,引用其元素的count
个值?
预期输出为:
count sum
1 1 10
2 3 45
3 2 25
4 4 75