我是“R”的新手,我有一个问题是保持变量的变化。这是我的代码:
recursiveCall <- function(x, N)
{
x[2^(N-1)+1] <- x[2^(N-1)+1] + (x[1] + x[2^N+1] ) / 2
if (N>1) {
recursiveCall(x[1..2^(N-1)+1], N-1)
recursiveCall(x[2^(N-1)+1..N], N-1)
}
#cat("Wmodif = ", x, "\n")
}
PaulLevyBrownianMotion <- function(N)
{
cat("Paul Levy construction for N = ", N, "\n")
W = rnorm(2^N+1, 0, 1)
W[1] <- 0
cat("Wstandard = ", W, "\n")
recursiveCall(W, N)
return (W)
}
但W不记得连续recursiveCall的变化。我应该写什么来保持第二行与输出中的第三行相似?此外,如果您对我的代码有任何建议,我将很高兴听到他们。
以下是我要对第一个答案做的事情:
recursiveCall <- function(x, N)
{
x[2^(N-1)+1] <- x[2^(N-1)+1] + (x[1] + x[2^N+1] ) / 2
if (N>1) {
x[1:2^(N-1)+1] <- [recursiveCall(x[1:2^(N-1)+1], N-1)
x[2^(N-1)+1:2^N] <- recursiveCall(x[2^(N-1)+1:2^N], N-1)
}
#cat("Wmodif = ", x, "\n")
return x
}
PaulLevyBrownianMotion <- function(N)
{
cat("Paul Levy construction for N = ", N, "\n")
W = rnorm(2^N+1, 0, 1)
W[1] <- 0
cat("Wstandard = ", W, "\n")
W <- recursiveCall(W, N)
return (W)
}
谢谢,Niels
答案 0 :(得分:2)
参数通过R中的值传递(关于它的更多内容,但这将作为引物)。因此,在函数内更改它们不会改变它们的“外部”版本。 根据你的需要,改变
recursiveCall <- function(x, N)
{
x[2^(N-1)+1] <- x[2^(N-1)+1] + (x[1] + x[2^N+1] ) / 2
cat("Wmodif = ", x, "\n")
return(x)
}
然后你用它作为:
PaulLevyBrownianMotion <- function(N)
{
cat("Paul Levy construction for N = ", N, "\n")
W = rnorm(2^N+1, 0, 1)
W[1] <- 0
cat("Wstandard = ", W, "\n")
W<-recursiveCall(W, N)
return (W)
}