0

I am looking for a way to sequentially label each unique event in a column.

For example,

df
  x
1 A
2 A
3 B
4 C
5 C
6 D

would result in:

df
  x event
1 A     1
2 A     1
3 B     2
4 C     3
5 C     3
6 D     4

I found I could do this using a loop such as

events <- unique(df$x)
for(i in 1:length(events){
  df$event[df$x == events[i]] <- i
}

but I would like to find a dpylr solution if possible.

Levente
  • 13
  • 3

2 Answers2

0

Try this:

# example data
set.seed(123)

df <- data.frame(
  x = sample(LETTERS[1:5], 10, replace = TRUE)
)
df <- df[order(df$x), , drop = FALSE]

# Label unique event
df$event <- as.numeric(factor(df$x))

df
#>    x event
#> 8  A     1
#> 3  B     2
#> 4  B     2
#> 9  B     2
#> 1  C     3
#> 2  C     3
#> 5  C     3
#> 10 C     3
#> 7  D     4
#> 6  E     5

Created on 2021-11-26 by the reprex package (v2.0.1)

stefan
  • 90,330
  • 6
  • 25
  • 51
0

Here you go:

df <- tibble(x= c("A", "A","B","C","C","D")) 

df1 <- tibble(x = unique(df$x),
              event = seq(1,length(x),1))

res <- left_join(df, df1, by="x")

Bloxx
  • 1,495
  • 1
  • 9
  • 21