Sequence of Repeated Values in R

让人想犯罪 __ 提交于 2019-11-26 01:53:58

问题


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!


回答1:


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)



回答2:


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.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

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 be c(1,1,2,3,3).



来源:https://stackoverflow.com/questions/6432067/sequence-of-repeated-values-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!