[英]How to write and calculate Sum/ Product (of a function) in R
Assuming that I have a function, let's say f(x)
.假设我有一个 function,比方说f(x)
。
How can I write the product or sum of this function for given limits in x.对于 x 中的给定限制,我如何写出这个 function 的乘积或总和。
For instance product of f
for x=1
until x=5
f(1)*f(2)*f(3)*f(4)*f(5)
例如x=1
直到x=5
的 f 乘积f
f(1)*f(2)*f(3)*f(4)*f(5)
Additionally I need to figure this out for sums/double sums.另外,我需要计算出总和/双总和。 Consider f(x,y)
and the sum while x runs from 1 to 3 and y runs from 0 to x-1.考虑f(x,y)
和 x 从 1 到 3 且 y 从 0 到 x-1 的总和。 If written in mathematica, it would be this: Sum[f[x, y], {x, 1, 3}, {y, 0, x - 1}]
and the output would be this f[1, 0] + f[2, 0] + f[2, 1] + f[3, 0] + f[3, 1] + f[3, 2]
如果用 mathematica 编写,它将是这样的: Sum[f[x, y], {x, 1, 3}, {y, 0, x - 1}]
和 output 将是这个f[1, 0] + f[2, 0] + f[2, 1] + f[3, 0] + f[3, 1] + f[3, 2]
f
is not defined for simplicity.为简单起见,未定义f
。
EDIT: example as requested:编辑:要求的例子:
f <- function (x,y) {
x + 2*y
}
Calculate sum where x runs from 1 to 3 and y runs from 0 to x-1.计算总和,其中 x 从 1 到 3,y 从 0 到 x-1。 (this is equal to 22 btw) (顺便说一句,这等于 22)
You can do this:你可以这样做:
f <- function (x,y) {
x + 2*y
}
)
#calculate f for all combinations
tmp <- outer(1:3, 0:2, f)
#discard undesired combinations and sum
sum(tmp[lower.tri(tmp, diag = TRUE)])
#[1] 22
Alternatively you can use a loop to create the desired combinations only.或者,您可以使用循环仅创建所需的组合。 This is much slower:这要慢得多:
inds <- lapply(1:3, function(x) data.frame(x = x, y = 0:(x-1)))
inds <- do.call(rbind, inds)
sum(do.call(f, inds))
#[1] 22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.