I have a database as follows:
CNPJ data dataquebra alto
2222 201603 201711 s
2222 201511 0 s
2222 201702 201711 s
2222 201704 201711 s
3333 201601 201711 s
3333 201509 0 s
3333 201512 0 s
3333 201607 201711 s
3333 201706 201711 s
1111 201701 201711 s
4444 201503 201605 s
4444 201503 201605 s
9999 201605 201712 s
9999 201511 0 s
9999 201704 201712 s
9999 201603 201712 s
I need to filter the values that the alto
variable is as s
. I want all values of dataquebra
for each CNPJ
to be equal. But realize that some of these values are zero.
So, replace the occurrences of dataquebra
that are equal to 0 by the other value that is not 0 in that variable.
I thought about using dplyr
and started as follows:
library(dplyr)
dados<-dados %>%
group_by(CNPJ) %>%
filter(alto=="s") %>%
mutate(x_lag = lag(dataquebra, order_by = data))
dados<-dados %>%
group_by(CNPJ) %>%
filter(alto=="s") %>%
mutate(x_lead = lead(dataquebra, order_by = data))
dados$dataquebra<-ifelse(dados$dataquebra==0 & !is.na(dados$x_lag),
dados$x_lag, dados$dataquebra)
dados$dataquebra<-ifelse(dados$dataquebra==0 & !is.na(dados$x_lead),
dados$x_lead, dados$dataquebra)
But for some reason it did not work.