r - Count changes to contents of a character vector -
this question has answer here:
i have data_frame character variable x changes in time. want count number of times changes, , fill new vector count.
df <- data_frame( x = c("a", "a", "b", "b", "c", "b"), wanted = c(1, 1, 2, 2, 3, 4) ) x wanted 1 1 2 1 3 b 2 4 b 2 5 c 3 6 b 4 this similar to, different rle(df$x), return
run length encoding lengths: int [1:4] 2 2 1 1 values : chr [1:4] "a" "b" "c" "b" i try rep() output. have tried this, awfully close, not reasons can't figure out immediately:
df %>% mutate( try_1 = cumsum(ifelse(x == lead(x) | is.na(lead(x)), 1, 0)) ) source: local data frame [6 x 3] x wanted try_1 1 1 1 2 1 1 3 b 2 2 4 b 2 2 5 c 3 2 6 b 4 3 it seems there should function directly, haven't found in experience.
try dplyr code:
df %>% mutate(try_1 = cumsum(ifelse(x != lag(x) | is.na(lag(x)), 1, 0))) x wanted try_1 1 1 1 2 1 1 3 b 2 2 4 b 2 2 5 c 3 3 6 b 4 4 yours saying: increment count if value same following row's value, or if following row's value na.
this says: increment count if variable on row either different 1 on previous row, or if there wasn't 1 on previous row (e.g., row 1).
Comments
Post a Comment