我想生成月份编号以及值列表。问题是该列表不是12个月的完整2次重复。第一年为12年,第二年为10年。
tibble(value=rnorm(22))
我尝试过的一些事情是rep(1:12,2)
,认为序列会在数据帧长度结束时停止。我也用同样的思路尝试了seq_along(along.with=value,1:12)
。
你想要length.out
参数rep()
:
rep(1:12, length.out = 22)
这使
> rep(1:12, length.out = 22)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10
我们得到这个是因为,来自?rep
:
‘length.out’ may be given in place of ‘times’, in which case ‘x’
is repeated as many times as is necessary to create a vector of
this length. If both are given, ‘length.out’ takes priority and
‘times’ is ignored.
我会推出22个月,然后使用模运算符来获得后续年份的数月
library(dplyr)
tibble(value=rnorm(22)) %>%
mutate(month=1:22,
month=ifelse(month%%12==0, 12, month%%12)