按顺序创建重复值序列? [英] Create sequence of repeated values, in sequence?
本文介绍了按顺序创建重复值序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个重复数字的序列,即 1 1 ... 1 2 2 ... 2 3 3 ... 3 等.
我的实现方式是:
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.
如何将N个整数依次重复M次?
- 我尝试嵌套
seq()
和rep()
但这并没有达到我想要的效果. - 我显然可以编写一个 for 循环来做到这一点,但应该有一种内在的方式来做到这一点!
- I tried nesting
seq()
andrep()
but that didn't quite do what I wanted. - I can obviously write a for-loop to do this, but there should be an intrinsic way to do this!
推荐答案
你错过了 rep()
的 each=
参数:
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)
这篇关于按顺序创建重复值序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文