2

This code is showing me this error: "number of items to replace is not a multiple of replacement length". I cannot figure out what the problem is.

So here is the code:

k <- c(0,0,0,0);
x <-30;
t <- c(10,20,30,35);
x1 <- x+t;
for(i in 1:4)
{
   k[i] <- 0:(100-x1[i]-1);
}

I would be grateful if someone could help me concerning this. Thank you in advance.

Jaime Caffarel
  • 2,401
  • 4
  • 30
  • 42
A.Ruhomaun
  • 13
  • 1
  • 1
  • 4
  • 1
    You have `k` with length of 4 and in loop, it is assigning to > 4 elements. I think you need `k <- vector('list', 4)` and in the loop `k[[i]] <- ...` – akrun Nov 12 '16 at 12:35

1 Answers1

1

As @akrun commented, you first pre-allocate a list of length 4 for the vectors of different lengths:

k <- vector('list', 4)
x <- 30
t <- c(10, 20, 30, 35)
x1 <- x + t

for(i in 1:4) k[[i]] <- 0:(100 - x1[i] - 1)

>k
#[[1]]
 #[1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#[33] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

#[[2]]
 #[1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#[33] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
# etc

By the way, you don't need the semi-colons or even the curly braces since the loop fits on one line.

Joe
  • 8,073
  • 1
  • 52
  • 58