I try to return the Y array from the second loop. I expect it to be (n - [k 2]) length but I get output of n length array
a1q1 <- function (n , j , k , m, X0) {
X <- numeric(length=n)
Xn <- X0
for (i in 1:n) {
Xn <- (103515245*Xn 12345) %% 2^32
X[i] <- Xn
}
Y <- numeric(length=n - k - 1)
for (i in k 2:n) {
Y[i - k - 1] <- (X[i - j] X[i - k]) %% m
}
return (Y)
}
Z <- a1q1(100, 5, 90, 11, 0)
Z
# [1] 6 5 8 3 1 10 1 1 9 6 2 2 5 7 NA NA NA NA NA NA NA NA NA NA NA NA
# [27] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# [53] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# [79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
CodePudding user response:
This often catches me too. You need to put parentheses around k 2
, in the second for
loop.. Try this minor adjustment below:
for (i in (k 2):n) {
Y[i-k-1] <- (X[i-j] X[i-k]) %% m
}
CodePudding user response:
@langtang has shown what you need to do.
The problem is operator precedence:
> 1 2:3
[1] 3 4
> (1 2):3
[1] 3
It is often a good idea to use parenthesis to avoid things like this, and it makes the code easier to read.