1

I want to create the following vector using a, b, c repeating each letter thrice:

BB<-c("a","a","a","b","b","b","c","c","c")

This is my code:

Alphabet<-c("a","b","c")
AA<-list()
for(i in 1:3){
  AA[[i]]<-rep(Alphabet[i],each=3)
}
BB<-do.call(rbind,AA)

But I am getting a dataframe:

    dput(BB)
structure(c("a", "b", "c", "a", "b", "c", "a", "b", "c"), .Dim = c(3L, 
3L))

What I am doing wrong?

Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22
runjumpfly
  • 319
  • 1
  • 10

4 Answers4

1

As Akrun mentioned we can use the same rep function create a vector which consists of letters a,b,c

A <- c("A","B","C")

Apply rep function for the same vector, use each as sub function

AA <- rep(A,each=3)

print(AA)

[1] "A" "A" "A" "B" "B" "B" "C" "C" "C"
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22
1

You should use c function to concatenate, not the rbind. This will give you vector.

Alphabet<-c("a","b","c")
AA<-list()
for(i in 1:3){
  AA[[i]]<-rep(Alphabet[i],each=3)
}
BB<-do.call(c,AA)

Akrun comment is also true, if thats what you want.

Kumar Manglam
  • 2,780
  • 1
  • 19
  • 28
1

You can also concatenate the rep function like so: BB <- c(rep("a", 3), rep("b", 3), rep("c", 3))

ringgord
  • 65
  • 6
  • Thanks for response. +1 for the trick. Actually I had a long list containing names, and I wanted to create a vector repeating each one consecutively for a certain number of times. – runjumpfly Nov 15 '16 at 12:34
0

Here is a solution but note this form or appending is not efficient for large input arrays

Alphabet <- c("a","b","c")
bb <- c()
for (i in 1:length(Alphabet)) {
  bb <- c(bb, rep(Alphabet[i], 3))
}
Dirk Nachbar
  • 542
  • 4
  • 16
  • Please, do not encourage newbies to use for loops in R whenthere are vectorized functions available, e.g, `rep(c("A","B","C"), each=3)` - Thank you. – Uwe Nov 15 '16 at 12:43