按顺序创建重复值的序列?

我需要一个重复的数字序列,也就是 1 1 ... 1 2 2 ... 2 3 3 ... 3 etc.。我实现这个的方法是:

  nyear <- 20
names <- c(rep(1,nyear),rep(2,nyear),rep(3,nyear),rep(4,nyear),
rep(5,nyear),rep(6,nyear),rep(7,nyear),rep(8,nyear))

这种方法很有效,但是很笨拙,而且显然不能很好地伸缩。

如何按顺序重复 N 个整数 M 次?

  • 我尝试嵌套 seq()rep(),但这并没有完全做我想要的。
  • 我当然可以编写一个 for 循环来完成这项工作,但是应该有一种内在的方法来完成这项工作!
159353 次浏览

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>

so your example can be done with a simple

R> rep(1:8, each=20)

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1  0.891  1
2 -1.13   1
3 -0.500  1
4 -1.12   1
5 -0.0187 1
6  0.420  2
7 -0.449  2
8  0.365  2
9  0.526  2
10  0.466  2
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))


[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5