Create sequence of repeated values, in sequence?
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)
How to create a sequence column for repeated values?
data$sequence <- unlist(lapply( with(data, rle(count)$lengths), seq_len))
data
ID count sequence
1 1 2 1
1.1 1 2 2
2 2 4 1
2.1 2 4 2
2.2 2 4 3
2.3 2 4 4
3 3 6 1
3.1 3 6 2
3.2 3 6 3
3.3 3 6 4
3.4 3 6 5
3.5 3 6 6
4 4 10 1
4.1 4 10 2
4.2 4 10 3
4.3 4 10 4
4.4 4 10 5
4.5 4 10 6
4.6 4 10 7
4.7 4 10 8
4.8 4 10 9
4.9 4 10 10
Sequence with repeating numbers
Another option
library(dplyr)
df %>%
mutate(pair = as.integer(gl(n(), 2, n())))
# id color pair
#1 1 red 1
#2 2 red 1
#3 3 red 2
#4 4 red 2
#5 5 red 3
#6 6 blue 3
#7 7 blue 4
#8 8 blue 4
#9 9 blue 5
#10 10 blue 5
Or with rep
and cumsum
df %>%
mutate(pair = cumsum(rep(c(TRUE, FALSE), length.out = n())))
Or much simpler case with base R
df$pair <- c(TRUE, FALSE)
df$pair <- cumsum(df$pair)
Repeating a repeated sequence
You can do it with a single rep
call. The each
and times
parameters are evaluated sequentially with the each
being done first.
rep(1:4, times=3, each=3) # 'each' done first regardless of order of named parameters
#[1] 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4
How to generate repeating numbers in sequence
Hierarchical query might help to produce result you posted:
SQL> with
2 c1 as
3 (select lpad(1 + level - 1, 2, '0') col1
4 from dual
5 connect by level <= 12
6 ),
7 c2 as
8 (select lpad(1 + level - 1, 2, '0') col2
9 from dual
10 connect by level <= 5
11 )
12 select c1.col1, c2.col2
13 from c1 cross join c2
14 order by c1.col1, c2.col2;
CO CO
-- --
01 01
01 02
01 03
01 04
01 05
02 01
02 02
02 03
02 04
02 05
03 01
03 02
<snip>
11 04
11 05
12 01
12 02
12 03
12 04
12 05
60 rows selected.
SQL>
Oracle: create sequence number for repeated rows
select id, value, row_number() over (partition by value order by id) as seq
from your_table;
Related Topics
Select Groups With More Than One Distinct Value
How to Use an Image as a Point in Ggplot
How to Merge Color, Line Style and Shape Legends in Ggplot
Wrap Long Axis Labels Via Labeller=Label_Wrap in Ggplot2
Geom_Rect and Alpha - Does This Work With Hard Coded Values
How to Subtract/Add Days From/To a Date
Repeat Rows of a Data.Frame N Times
How to Sum a Numeric List Elements
Convert Type of Multiple Columns of a Dataframe At Once
Painless Way to Install a New Version of R
How R Formats Posixct With Fractional Seconds
Dplyr::Select Function Clashes With Mass::Select
How to Replace Na Values in a Table For Selected Columns
Replace Missing Values With Column Mean
Dplyr: How to Use Group_By Inside a Function