将R矢量拆分为均匀大小的块

时间:2017-01-22 17:25:20

标签: r list for-loop vector

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

# 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

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

1 个答案:

答案 0 :(得分:0)

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

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

更正后的代码:

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

或者:

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

输出:

[[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