Reputation: 39
I am trying to store values into a numeric array using a sliding window. However, I am not able to store values using the following code -
d=c(1:1000)
e=0
for (i in d){
a[e]=c(i:i+10)
e=e+1
}
I am looking to see -
a[1]=1 2 3 4 5 6 7 8 9 10
a[2]=2 3 4 5 6 7 8 9 10 11
Upvotes: 0
Views: 57
Reputation: 26353
You might use embed
and then apply
to reverse each row
x <- 1:20
t(apply(embed(x, 10), 1, rev))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 1 2 3 4 5 6 7 8 9 10
# [2,] 2 3 4 5 6 7 8 9 10 11
# [3,] 3 4 5 6 7 8 9 10 11 12
# [4,] 4 5 6 7 8 9 10 11 12 13
# [5,] 5 6 7 8 9 10 11 12 13 14
# [6,] 6 7 8 9 10 11 12 13 14 15
# [7,] 7 8 9 10 11 12 13 14 15 16
# [8,] 8 9 10 11 12 13 14 15 16 17
# [9,] 9 10 11 12 13 14 15 16 17 18
#[10,] 10 11 12 13 14 15 16 17 18 19
#[11,] 11 12 13 14 15 16 17 18 19 20
This might be a faster option of the same idea
out <- embed(x, 10)
out[, ncol(out):1]
Upvotes: 2
Reputation: 4480
Returning a list:
first <- c(0:9)
a <-lapply(1:1000, function(x) first+x)
a[1] 1 2 3 4 5 6 7 8 9 10
a[2] 2 3 4 5 6 7 8 9 10 11
a[3] 3 4 5 6 7 8 9 10 11 12
Upvotes: 1
Reputation: 6720
Does it need to be an array? The following makes a matrix:
sapply(1:10, function(i) i:(i+10))
This may work depending on the downstream application. If it has to be an array, check out How to convert matrix into array?
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 2 3 4 5 6 7 8 9 10
[2,] 2 3 4 5 6 7 8 9 10 11
[3,] 3 4 5 6 7 8 9 10 11 12
[4,] 4 5 6 7 8 9 10 11 12 13
[5,] 5 6 7 8 9 10 11 12 13 14
[6,] 6 7 8 9 10 11 12 13 14 15
[7,] 7 8 9 10 11 12 13 14 15 16
[8,] 8 9 10 11 12 13 14 15 16 17
[9,] 9 10 11 12 13 14 15 16 17 18
[10,] 10 11 12 13 14 15 16 17 18 19
[11,] 11 12 13 14 15 16 17 18 19 20
Upvotes: 1