给定三个输入向量v
、a
和m
以下函数:
f1 <- function(v, m, a) {
o = outer(m, v, ">")
rowSums(t(t(o) * a ))
}
我正在尝试更有效地重写。这是我的尝试:
f2 <- function(v, m, a) {
vm=c(m, v)
index = c(rep(0, length(m)), rep(1, length(v)))
index1 = index[order(vm)]
cumsum1 = cumsum(index1)
r = cumsum1[index1 == 0]
cumsum.a = cumsum(a)
cumsum.a[r]
}
对于以下输入,这两个函数给出相同的结果:
v = c(0, 0.11, 0.17, 0.31, 0.63)
a = c(11.41, 9.40, 7.11, 2.80, 0.27)
m = c(0.03, 0.097, 0.14, 0.19, 0.26, 0.31, 0.46, 0.63, 1.13)
f1(v, m, a)
# [1] 11.41 11.41 20.81 27.92 27.92 27.92 30.72 30.72 30.99
f2(v, m, a)
# [1] 11.41 11.41 20.81 27.92 27.92 27.92 30.72 30.72 30.99
但不适用于:
w = c(0.07, 0.21, 0.30, 0.62, 1.63)
f1(w, m, a)
# [1] 0.00 11.41 11.41 11.41 20.81 27.92 27.92 30.72 30.72
f2(w, m, a)
# [1] 11.41 11.41 11.41 20.81 27.92 27.92 30.72 30.72
你能帮我修复一下,让它给出与两组输入f2
相同的结果吗?f1