重复向量到第n个元素

时间:2016-10-07 16:51:08

标签: r loops vector seq rep

我想重复的载体是:

> months2014
[1] "07" "08" "09" "10" "11" "12"

我想根据定义第n个值的向量重复它:

> num_times
  [1]  6  6  6  6  5  6  6  5  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6
 [33]  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6 12  6  6  6  6  6  6  6 12  6  6  6  6  6  6
 [65]  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6 12  6
 [97]  6  6 12  6  6  6  6  6  6  6  6 12  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  6  2  6  6
[129]  6 12  6  6  6  6  6  6

我用这个循环得到以下输出:

for (i in num_times)  
  print(months2014[1:i])

[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" ## repeated upto the 5th element
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" "12"
[1] "07" "08" "09" "10" "11" ## repeated up to the 6th element

如果你看一下num_times矢量,它也有12.因此我也得到了这个结果:

[1] "07" "08" "09" "10" "11" "12" NA   NA   NA   NA   NA   NA

months2014中只有6个元素,所以我得到了NA。我实际上希望它重新启动并获得如下输出:

[1] "07" "08" "09" "10" "11" "12" "07   "08" "09"   "10"   "11"   "12"

我有三个问题:

1)如何保存循环输出?我尝试创建一个空向量并将结果放入其中,但这不起作用:

temp_vec <- c()
for (i in num_times)  
  temp_vec <- print(months2014[1:i])

2)如何修复NA?

3)必须有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

经过测试,这似乎有效:

sapply(num_times,function(x) rep(months2014,length.out=x)

如果num_times中的值高于months214的长度,它会输出一个列表并重复序列:

[[1]]
[1] "07" "08" "09" "10" "11" "12"

[[2]]
[1] "07" "08" "09" "10" "11" "12"

[[3]]
[1] "07" "08" "09" "10" "11" "12"

[[4]]
[1] "07" "08" "09" "10" "11" "12"

[[5]]
[1] "07" "08" "09" "10" "11"

[[6]]
 [1] "07" "08" "09" "10" "11" "12" "07" "08" "09" "10" "11" "12"