The sequence of repeated values ​​in R

This is a very simple question, but it annoys me, so I ask.

I need a sequence of repeating numbers, i.e. 1 1 ... 1 2 2 ... 2 3 3 ... 3 etc. The way I did 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 does not scale well. How do I repeat N integers M times each in a sequence? I tried nesting seq () and rep (), but this is not quite the way I wanted. I can obviously write a for loop that will do this, but it also seems awkward - there must be an internal way to do this!

+62
r seq
Jun 21 '11 at 21:15
source share
2 answers

You skipped 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) 
+131
Jun 21 2018-11-21T00:
source share

For your example, Dirk's answer is perfect. If you instead had a data frame and you want to add this kind of sequence as a column, you can also use the group from groupdata2 (disclaimer: my package) to eagerly split the data points 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 are a number of methods for creating this kind of group factor. For example, by the number of groups, the list of group sizes, or by the presence of groups, if the value in some column differs from the value in the previous row (for example, if the column has the value c("x","x","y","z","z") the grouping coefficient will be c(1,1,2,3,3) .

0
Jul 24 '19 at 22:14
source share



All Articles