我有一个数据框:
a <- data.frame(c(1:10))
我想添加一个像这样的列:
a$Groups <- c("Group1","Group1","Group1",
"Group2","Group2","Group2","Group2","Group2",
"Group3","Group3")
但我不想重复每一个元素。
谢谢你们!
答案 0 :(得分:0)
尝试
a$Groups <- c(rep("Group1", 3),
rep("Group2", 5),
rep("Group3", 2))
并查看
?rep
答案 1 :(得分:0)
改编@ alko989的答案是使用paste
和rep
:
> paste0("Group", rep(1:3, c(3, 5, 2)))
[1] "Group1" "Group1" "Group1" "Group2" "Group2" "Group2" "Group2"
[8] "Group2" "Group3" "Group3"
或者,效率更高(我认为):
rep(paste0("Group", 1:3), c(3, 5, 2))