Sequence of Repeated Values in R

2019-01-03 09:54发布

This is a very basic question, but it's annoying me, so I'm asking.

I need a sequence of repeated numbers, i.e. 1 1 ... 1 2 2 ... 2 3 3 ... 3 etc. The way I implemented this was

  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))

which works, but is clumsy, and obviously doesn't scale well. How do I repeat the N integers M times each in sequence? I tried nesting seq() and rep() but that didn't quite do what I wanted. I can obviously write a for loop that will do it, but this also seems clumsy -- there should be an intrinsic way to do this!

标签: r seq
1条回答
Luminary・发光体
2楼-- · 2019-01-03 10:56

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)
查看更多
登录 后发表回答