按顺序创建重复值序列?
我需要一系列重复的数字,即 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))
它有效,但很笨拙,并且显然不能很好地扩展。
如何按顺序重复 N 个整数 M 次?
- 我尝试嵌套
seq()
和rep()
但这并不完全做我想做的事。 - 显然我可以编写一个 for 循环来执行此操作,但应该有一种内在的方法来执行此操作!
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()
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您错过了
rep()
的each=
参数:因此您的示例可以通过简单的方法来完成
You missed the
each=
argument torep()
:so your example can be done with a simple
另一个
base R
选项可以是gl()
:其中输出是一个因子:
如果需要整数,您可以将其转换:
Another
base R
option could begl()
:Where the output is a factor:
If integers are needed, you can convert it:
对于你的例子,德克的答案是完美的。如果您有一个数据框并希望将这种序列添加为一列,您还可以使用 groupdata2 (免责声明:我的包)中的
group
将数据点贪婪地分成组。创建这种分组因素的方法有很多种。例如,按组数、组大小列表,或者当某列中的值与前一行中的值不同时让组开始(例如,如果列是
c("x","x", "y","z","z")
分组因子将为c(1,1,2,3,3)
。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.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 bec(1,1,2,3,3)
.