add column that shows how many times a value has repeated from that row back

Asked

Viewed 57 times

4

I’m having trouble creating a column that shows how many times a row has repeated itself, but not in the entire dataset, but in that line back.

Ex:

NOME     ANO       MES    COLUNA_QUE_QUERO_CRIAR
A        2016      4          1
A        2016      4          2
B        2016      5          1
B        2016      5          2
B        2016      5          3

what I have managed to do is that in this column is the value of the whole dataset. Type, pro A is 2 and 2, pro B 3 and 3, but I want this count.

what I did that gave this result that I did not wish was

dataset %>% group_by(NOME) %>% mutate('COLUNA_QUE_QUERO_CRIAR' = n())

Someone can help me?

1 answer

8


Only use the function seq

library(dplyr)
dataset %>% 
  group_by(NOME) %>% 
  mutate(COLUNA_QUE_QUERO_CRIAR = seq(1:n()))
  • bro, I’m dumb mt. I knew this apóskdakdoapksdopakdkaopdopakd. Thanks man!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.