0

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.

4
  • 1
    Just use rep(1:3,each=4). Commented Oct 2, 2015 at 15:55
  • what is the age object? And what is n2? Commented Oct 2, 2015 at 15:57
  • The age object should be a list of length n2. I would then like to concatenate these n lists of length n2 to form a list of length 3n2. In reality n2 = >30 and n>70. Commented Oct 2, 2015 at 16:01
  • Thanks nicola. So simple! I had previously tried rep(1:3,4) and did not know about each. Commented Oct 2, 2015 at 16:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.