Tomas
Tomas

Reputation: 59505

unique() but only on consecutive rows

I am looking for equivalent of unique(), but done only on the consecutive rows. I.e., in the following example:

df <- data.frame(a = rep(c(1:3,1:3), each = 3), b = rep(c(4:6,4:6), each = 3))
unique(df)
#  a b
#1 1 4
#4 2 5
#7 3 6

I want to actually get:

function_I_am_looking_for(df)
#   a b
#1  1 4
#4  2 5
#7  3 6
#10 1 4
#13 2 5
#16 3 6

Upvotes: 2

Views: 98

Answers (1)

akrun
akrun

Reputation: 887148

We can use rleid to create a grouping variable and slice the first row

library(dplyr)
library(data.table)
df %>% 
   group_by(grp = rleid(a, b)) %>%
   slice(1) %>%
   ungroup %>%
   select(-grp)
# A tibble: 6 x 2
#      a     b
#  <int> <int>
#1     1     4
#2     2     5
#3     3     6
#4     1     4
#5     2     5
#6     3     6

Or the same with data.table syntax, grouped by rleid of 'a', b', extract the first elements row index (.I) and subset the rows with that

setDT(df)[df[, .I[1], .(rleid(a, b))]$V1]

Or using unique with by

unique(setDT(df)[, grp := rleid(a, b)], by = "grp")

Or, OP prefered version, solution for general data.frame using just a base functionality:

unique(cbind(rleidv(df), df))[,-1]

Upvotes: 4

Related Questions