我想将post减去datestamp-1的所有元素与datestamp-2的第一个元素相加,并对datestamp-2的第二个元素重复相同的操作,依此类推
datestamp1 datestamp2 load_percent
2019-05-28 2019-05-25 0.01883
2019-05-29 2019-05-26 0.72340预期结果如下所述。
datestamp1 datestamp2 weighted_index
2019-05-28 2019-05-25 2.95
2019-05-29 2019-05-26 2.20逻辑存在
1. 2019-05-28 - 2019-05-25 = 3 * 0.01 = 0.056
2. 2019-05-29 - 2019-05-25 = 4 * 0.72 = 2.8930.056与2.893之和是2.95.
类似的
3. 2019-05-28 - 2019-05-26 = 2 * 0.01 = 0.037
4. 2019-05-29 - 2019-05-26 = 3 * 0.72 = 2.1700.037和2.170的和是2.20
发布于 2019-05-28 22:05:46
使用sapply你可以做到
df$weighted_index <- sapply(df$datestamp2, function(x)
sum((df$datestamp1 - x) * df$load_percent))
df
# datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25 0.01883 2.95009
#2 2019-05-29 2019-05-26 0.72340 2.20786确保您的列datestamp1和datestamp2属于Date类。如果它们不是,首先将它们转换为日期,然后使用上面的代码。
df[1:2] <- lapply(df[1:2], as.Date)发布于 2019-05-28 22:07:34
我们可以使用outer获取两个日期列之间的差值,然后使用'load_percent‘获取产品的colSums
df1$weighted_index <- with(df1, colSums(outer(datestamp1,
datestamp2, FUN = `-` ) * load_percent))
df1
# datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25 0.01883 2.95009
#2 2019-05-29 2019-05-26 0.72340 2.20786数据
df1 <- structure(list(datestamp1 = structure(c(18044, 18045), class = "Date"),
datestamp2 = structure(c(18041, 18042), class = "Date"),
load_percent = c(0.01883, 0.7234)), row.names = c(NA, -2L
), class = "data.frame")https://stackoverflow.com/questions/56342905
复制相似问题