I am trying to mutate and lag the same column in R dplyr, per the reproducible code at the bottom of this post. That code doesn't give my what I'm looking for. What am I doing wrong?
Running the code gives me these incorrect results, where column nameCntMult is the one I'm trying to lag:
> dataFill
# A tibble: 6 x 4
Name Code nameCnt nameCntMult
<chr> <dbl> <int> <dbl>
1 R 0 1 1
2 R 0 2 2
3 T 0 1 1
4 R 0 3 3
5 N 1 1 NA
6 N 1 2 2
When I'm looking for these results, rendered in XLS:
Reproducible code:
library(dplyr)
data <-
data.frame(
Name = c("R","R","T","R","N","N"),
Code = c(0,0,0,0,1,1)
)
dataFill <-data %>%
group_by(Name, Code) %>%
mutate(nameCnt = row_number())%>%
mutate(nameCntMult = nameCnt * 2) %>%
mutate(nameCntMult = ifelse(Code == 0, nameCnt, lag(nameCntMult))) %>%
ungroup()
dataFill
