0

Essentially, I am taking a list of emotions and trying to replicate each emotion on the list 6 times and then add them to a vector. For example:

emotions<-c("Happy","Sad","Angry")

will look like:

emotions2<-c("Happy","Happy","Happy","Happy","Happy","Happy","Sad","Sad","Sad","Sad","Sad","Angry","Angry","Angry","Angry","Angry","Angry")

Right now to do this, I am using a for loop but for some reason it's only replicating the first emotion, creating the vector, emotions2<-c("Happy","Happy","Happy","Happy","Happy","Happy").

My code looks like this: pmd.df3 is my data frame and Emotions is the new column in it where I'll store this info.

  pmd.df3$Emotions<-(
     for(ele in emotions){
       new.column<-replicate(6,ele)
       print(new.column)
     }
   )

Please let me know if you can help!

Aurélien Gasser
  • 3,043
  • 1
  • 20
  • 25
Andrew Colin
  • 155
  • 1
  • 11

2 Answers2

0

To achieve that, you can use lapply (to apply a function to each element of a list/vector) and unlist (to flatten the resulting list of lists):

pmd.df3$Emotions <- unlist(lapply(emotions, function(x) { rep(x, 6) }))

Full example:

emotions <- c("Happy", "Sad", "Angry")
pmd.df3 = data.frame(id = seq(1, 18))

pmd.df3$Emotions <- unlist(lapply(emotions, function(x) { rep(x, 6) }))
pmd.df3 
#    id Emotions
# 1   1    Happy
# 2   2    Happy
# 3   3    Happy
# 4   4    Happy
# 5   5    Happy
# 6   6    Happy
# 7   7      Sad
# 8   8      Sad
# 9   9      Sad
# 10 10      Sad
# 11 11      Sad
# 12 12      Sad
# 13 13    Angry
# 14 14    Angry
# 15 15    Angry
# 16 16    Angry
# 17 17    Angry
# 18 18    Angry
Aurélien Gasser
  • 3,043
  • 1
  • 20
  • 25
  • Can you tell me why my code did NOT work? It was working when I said "print" but as soon as I saved it as a vector it deleted all emotions but for the first one (which it did replicate 6 times). – Andrew Colin Jun 27 '17 at 21:38
  • @AndrewColin I'm not too familiar with using `print` in the code like you did, but I *think* what was going on is you didn't aggregate all the emotions in a single vector (`pmd.df3$Emotions <-` is expecting a single vector, not several). Also, if my answer is the correct one, feel free to mark it as accepted ;) – Aurélien Gasser Jun 27 '17 at 21:42
  • That logic makes sense to me. Thanks for the answer and explanation! – Andrew Colin Jun 28 '17 at 12:04
0

To piggyback off of shambalambala's answer, rep can handle this natively without needing lapply or a for loop.

emotions <- c("Happy", "Sad", "Angry")
pmd.df3 = data.frame(id = seq(1, 18))
pmd.df3$Emotions <- rep(emotions, each = 6)

   id Emotions
1   1    Happy
2   2    Happy
3   3    Happy
4   4    Happy
5   5    Happy
6   6    Happy
7   7      Sad
8   8      Sad
9   9      Sad
10 10      Sad
11 11      Sad
12 12      Sad
13 13    Angry
14 14    Angry
15 15    Angry
16 16    Angry
17 17    Angry
18 18    Angry
Eric Watt
  • 3,180
  • 9
  • 21