为什么我的 for 循环不遍历整个列表?

Why won't my for loop iterate over the whole list?

本质上,我正在制作一个情绪列表,并尝试将列表中的每种情绪复制 6 次,然后将它们添加到一个向量中。例如:

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

看起来像:

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

现在要做到这一点,我正在使用 for 循环,但出于某种原因,它只是复制了第一种情绪,创建了向量, emotions2<-c("Happy","Happy","Happy","Happy","Happy","Happy").

我的代码如下所示: pmd.df3 是我的数据框,Emotions 是其中的新列,我将在其中存储此信息。

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

如果你能帮上忙,请告诉我!

为此,您可以使用 lapply(将函数应用于 list/vector 的每个元素)和 unlist(展平列表的结果列表):

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

完整示例:

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

借助 shambalambala 的回答,rep 可以在本机处理此问题,而无需 lapply 或 for 循环。

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