将R矢量拆分为均匀大小的块[重复]

时间:2021-07-25 03:15:38

This question already has an answer here:

这个问题在这里已有答案:

This seems like it should be trivial, but the results are unexpected

这似乎应该是微不足道的,但结果是出乎意料的

# create empty list
list=c()
# create vector of one hundred 4s
fours=rep(4,100)
# for loop. Try to split into 10
for(i in seq(10)){
  # split into chunks: i=1, take fours[1:10]; i=2, fours[11:20]...
  # when i=10, should return fours[91:100]
  chunks=fours[1+10*(i-1):10*i]
  # add smaller lists of four back into bigger list
  list=c(list,chunks)
}
list
# returns  [1]  4  4  4  4  4  4  4  4  4  4 NA  4  4  4  4 NA NA NA NA NA NA  4  4 NA NA
[26] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

I would expect to just get back one hundred 4 values.

我希望能够获得一百四十四个值。

1 个解决方案

#1


0  

Following line needs to be corrected (parentheses to be added for proper arithmatic operation):

需要更正以下行(为正确的算术运算添加括号):

chunks=fours[1+10*(i-1):10*i]

Corrected code:

fours=rep(4,100)
chunks = list()
for(i in 1:10){
    chunks[[i]] = fours[(1+((i-1)*10)) : (10+((i-1)*10))]
}
chunks

Or:

fours=rep(4,100)
chunks = list()
for(i in 1:10){
    start = 1+((i-1)*10)
    chunks[[i]] = fours[ start : (9+start)]
}
chunks

Ouput:

[[1]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[2]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[3]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[4]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[5]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[6]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[7]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[8]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[9]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[10]]
 [1] 4 4 4 4 4 4 4 4 4 4

#1


0  

Following line needs to be corrected (parentheses to be added for proper arithmatic operation):

需要更正以下行(为正确的算术运算添加括号):

chunks=fours[1+10*(i-1):10*i]

Corrected code:

fours=rep(4,100)
chunks = list()
for(i in 1:10){
    chunks[[i]] = fours[(1+((i-1)*10)) : (10+((i-1)*10))]
}
chunks

Or:

fours=rep(4,100)
chunks = list()
for(i in 1:10){
    start = 1+((i-1)*10)
    chunks[[i]] = fours[ start : (9+start)]
}
chunks

Ouput:

[[1]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[2]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[3]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[4]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[5]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[6]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[7]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[8]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[9]]
 [1] 4 4 4 4 4 4 4 4 4 4

[[10]]
 [1] 4 4 4 4 4 4 4 4 4 4