0

I need to assign a value to rows based on another column. See example:

x <- c("A", "A", "A", "B", "A", "A", "C", "B", "B", "B", "A")

I need to have an output similar to this:

y <- c(1, 2, 3, 1, 1, 2, 1, 1, 2, 3, 1)

My sample data is,

df <- as.tibble(cbind(x,y))

df$y <- as.double(df$y)

I have tried

df1 <- df %>%
    mutate(
        z = ifelse(x != lag(x), 1, lag(z)+1)
    )

but it gives 1 after the second entry of the same kind;

x   y   z

A   1   NA

A   2   NA

A   3   1

B   1   1

A   1   1

A   2   2

C   1   1

B   1   1

B   2   2

B   3   1

A   1   1

Is there a function I can use to do this? I need to work in a context like:

df <- df %>% 

group_by(Group1, Group2) %>% 

mutate(TimesInARow <- function(x))

where Group1 and Group2 are factors, e.g. location or year.

Thank you in advance!

maydin
  • 3,225
  • 3
  • 9
  • 26
  • A tiny heads-up: avoid the `cbind` in `as.tibble(cbind`. `cbind` creates a matrix, which coerces all values to the same class. Just use `tibble(x = c(...), y = ...)` (see examples in `?tibble`). Cheers – Henrik Sep 30 '21 at 10:11

0 Answers0