user2568648
user2568648

Reputation: 3201

R Error in for loop

I would like to make several lists of numbers and then concatenate them i.e.

list 1 = 1, 1, 1, 1

list 2 = 2, 2, 2, 2

list 3 = 3, 3, 3, 3

final list = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3

I tried the following to create lists 1 to 3

ageseq <- c(1,2,3)
n <- 3
n2 <- 4

for (i in 1:n){
  for (j in 1:n){
    age[i] <- c(rep(ageseq[j],n2))
  }  
}

which produces the following error,

In age[i] <- c(rep(ageseq[j], n2)) :
  number of items to replace is not a multiple of replacement length

as age1, age2 and age3 do not exist.

What in my code is missing? In reality I need to concatenate over 70 lists of numbers.

Upvotes: 0

Views: 71

Answers (2)

cd1
cd1

Reputation: 16534

You can try:

unlist(lapply(1:3, rep, 4))

Upvotes: 0

JCollerton
JCollerton

Reputation: 3327

So the problem is that you are replacing an element of length one (age[i]) with an element of length four (rep(ageseq[j], n2)). You aren't concatenating the lists, you're trying to replace the number i element with a list of numbers, which leads to the warnings.

If you want to do it the way you've specified, you need to use the loop:

ageseq <- c(1,2,3)
n <- 3
n2 <- 4
age <- c()

for (j in 1:n){
  age <- c(age, rep(ageseq[j],n2))
}

Which will concatenate the separate lists into one as you wanted. Another option as someone put before is to use: age <- rep(1:3,each=4). To create the separate lists you could use the loop:

ageseq <- c(1,2,3)
n <- 3
n2 <- 4
age_list <- list()

for (j in 1:n){
  age_list[[j]] <- rep(ageseq[j],n2)
}

Then age_list[[1]] will be a list of ones, age_list[[2]] will be a list of twos etc.

Upvotes: 3

Related Questions