[英]Vectorized R function
I have to write a vectorized R function f that takes a vector x= (x_1, . . . , x_m) and a natural number n, and returns the value f_n(x) given by:我必须编写一个向量化的 R function f,它接受一个向量 x= (x_1, . . . , x_m) 和一个自然数 n,并返回由以下公式给出的值 f_n(x):
Example:例子:
> x = seq(-1, 3, by = 0.4)
> f(x,6) # here n=6
[1] 0.000000e+00 0.000000e+00 0.000000e+00
[4] 2.666667e-06 6.480000e-04 8.333333e-03
[7] 4.430667e-02 1.410800e-01 3.050933e-01
[10] 4.755467e-01 5.500000e-01
This is what I got:这就是我得到的:
f = function(x, n){
s = 0
for(j in 0:x)
s = s + (-1)^j*choose(n, j)*(x-j)^(n-1)
s/factorial(n-1)
}
x = seq(-1, 3, by = 0.4)
f(x,6)
Warning in 0:x: numerical expression has 11 elements: only the first used
[1] -8.333333e-03 -6.480000e-04 -2.666667e-06 2.666667e-06 6.480000e-04
[6] 8.333333e-03 4.481867e-02 1.574640e-01 4.294693e-01 9.901147e-01
[11] 2.025000e+00
Clearly it is not what it should be in the example.显然,这不是示例中应有的样子。 What did I do wrong here?我在这里做错了什么? TIA TIA
EDIT: Maybe using outer
and apply
might help with x
?编辑:也许使用outer
和apply
可能对x
有帮助?
Try this code.试试这段代码。 It can be modified to become tidier but maybe it can solve your problem in its current form.可以对其进行修改以变得更整洁,但也许它可以以当前形式解决您的问题。 I used both base R and purr
functions for iteration instead of for
loop but maybe for
loop alone can do the job.我使用 base R 和purr
函数进行迭代而不是for
循环,但也许for
循环本身就可以完成这项工作。
library(tidyverse)
n <- 6
x <- seq(-1, 3, by = 0.4)
x[x<= 0] <- 0
seq_fun <- function(x) seq(0, x)
d <- sapply(x, seq_fun)
fun <- function(r, t) {
sum((-1) ^ r *choose(n, r)*(r-t)^(n-1)) / factorial(n - 1)
}
as_vector(map2(d, x, fun))
This is a slightly different way of doing this solely based on base R:这是仅基于基数 R 的一种略有不同的方法:
x = seq(-1, 3, by = 0.4)
n <- 6
fn <- function(x, n) {
x[x <= 0] <- 0
sapply(x, function(x) {
Reduce(function(a, b) {
a + (-1) ^ b * (factorial(n)/(factorial(b) * factorial(n-b))) * (x - b) ^ (n-1)
}, seq(0, x), init = 0) * (1/factorial(n-1))
})
}
fn(x, 6)
[1] 0.000000e+00 0.000000e+00 0.000000e+00 2.666667e-06 6.480000e-04 8.333333e-03 4.430667e-02
[8] 1.410800e-01 3.050933e-01 4.755467e-01 5.500000e-01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.