[英]Unable to store values in a numeric array inside for loop
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
You might use embed
and then apply
to reverse each row 您可以使用embed
,然后apply
反转每一行
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]
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
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 [1] 1 2 3 4 5 6 7 8 9 10
a[2] 2 3 4 5 6 7 8 9 10 11 a [2] 2 3 4 5 6 7 8 9 10 11
a[3] 3 4 5 6 7 8 9 10 11 12 a [3] 3 4 5 6 7 8 9 10 11 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.