R中重复值的顺序

Wes*_*urr 71 r seq

这是一个非常基本的问题,但这让我烦恼,所以我问.

我需要一系列重复的数字,即1 1 ... 1 2 2 ... 2 3 3 ... 3等.我实现这个的方式是

  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))
Run Code Online (Sandbox Code Playgroud)

哪个有效,但很笨拙,显然不能很好地扩展.如何按顺序重复N次整数M次?我尝试嵌套seq()和rep(),但这并不是我想要的.我显然可以写一个for循环来做它,但这看起来也很笨拙 - 应该有一个内在的方法来做到这一点!

Dir*_*tel 142

你错过了这个each=论点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> 
Run Code Online (Sandbox Code Playgroud)

所以你的例子可以用一个简单的方法完成

R> rep(1:8, each=20)
Run Code Online (Sandbox Code Playgroud)


tmf*_*mnk 5

另一种base R选择可能是gl()

gl(5, 3)
Run Code Online (Sandbox Code Playgroud)

其中输出是一个因素:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

如果需要整数,可以将其转换:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Run Code Online (Sandbox Code Playgroud)