我想在列中重复值,这些值可能没有相同的重复量。
例如,我想创建一个名为“Week”的列,其中我将“第1周”重复10次,然后“第2周”重复20次,然后“第3周”重复30次。
现在我正在使用此代码,但它只允许我重复每个“周#”相同的次数。
df$Week <- rep(c("Week 1", "Week 2", "Week 3"), each = 10)
在这个例子中,我有第1周重复3次,第2周重复5次,第3周重复7次。我如何具体重复特定值的次数?
X Week
1 1.00 Week 1
2 2.00 Week 1
3 3.00 Week 1
4 4.00 Week 2
5 5.00 Week 2
6 6.00 Week 2
7 7.00 Week 2
8 8.00 Week 2
9 9.00 Week 3
10 10.0 Week 3
11 11.0 Week 3
12 12.0 Week 3
13 13.0 Week 3
14 14.0 Week 3
15 15.0 Week 3
答案 0 :(得分:3)
如何确定特定值重复的次数?
times
参数。来自?rep
:
times
一个整数值向量,给出(非负)次数,重复每个元素,如果长度为length(x)
,或重复整个向量,如果长度为1
> rep(c("Week 1", "Week 2", "Week 3"), times = c(10, 20, 30))
# repeats "Week 1" 10 times, "Week 2" 20 times, "Week 3" 30 times
答案 1 :(得分:0)
试试这个解决方案:
一周的通用列表
weeks<-c("Week 1", "Week 2", "Week 3")
从字符串中提取重复次数
repetition<-as.numeric(unlist(strsplit(weeks," "))[seq(2,length(weeks)*2,by=2)])*10
重复字符串
Week<-rep(weeks,repetition)
Week
[1] "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 1" "Week 2"
[12] "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2"
[23] "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 2" "Week 3" "Week 3" "Week 3"
[34] "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3"
[45] "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3" "Week 3"
[56] "Week 3" "Week 3" "Week 3" "Week 3" "Week 3"
将信息添加到data.frame
df$Week<-Week