按顺序创建重复值的顺序? [英] Create sequence of repeated values, in sequence?

查看:133
本文介绍了按顺序创建重复值的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个重复的数字序列,即1 1 ... 1 2 2 ... 2 3 3 ... 3 etc.我实现的方式是:

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() and rep() 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=参数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆