Repeat sequence by group

Viewed 2205

I have the following dataframe:

a <-  data.frame(
  group1=factor(rep(c("a","b"),each=6,times=1)),
  time=rep(1:6,each=1,times=2),
  newcolumn = c(1,1,2,2,3,3,1,1,2,2,3,3)
)

I'm looking to replicate the output of newcolumn with a rep by group function (the time variable is there for ordering purposes). In other words, for each group, ordered by time, how can I assign a sequence 1,1,2,2,n,n? I also need a general solution (in the case that groups are of differing number of rows, or I want to repeat values 3,10,n times).

For instance, I can generate that sequence with this: newcolumn=rep(1:3,each=2,times=2)

But that wouldn't work in a group by statement where group1 has differing rows.

2 Answers

We specify the length.out in the rep after grouping by 'group1'

library(dplyr)
a %>% 
  group_by(group1) %>% 
  mutate(new = rep(seq_len(n()/2), each = 2, length.out = n()))

NOTE: each and times are not used in the same call. Either we use each or times

EDIT: Based on comments from @r2evans

A data.table alternative:

library(data.table)
DT <- as.data.table(a[1:2])

DT[order(time),newcolumn := rep(seq_len(.N/2), each=2, length.out=.N),by=c("group1")]
DT
#     group1 time newcolumn
#  1:      a    1         1
#  2:      a    2         1
#  3:      a    3         2
#  4:      a    4         2
#  5:      a    5         3
#  6:      a    6         3
#  7:      b    1         1
#  8:      b    2         1
#  9:      b    3         2
# 10:      b    4         2
# 11:      b    5         3
# 12:      b    6         3
Related