-2

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.

Mark Miller
  • 12,483
  • 23
  • 78
  • 132
William Nowak
  • 25
  • 1
  • 4
  • from my first look, one dark mistake we all do is misisng out those `()` when having arithmetic operators aroung `:` while subsetting. – joel.wilson Jan 22 '17 at 17:40

1 Answers1

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
rnso
  • 23,686
  • 25
  • 112
  • 234