Replace 0's with previous non-zero value per ID (lag)
问题 How can I replace all 0's with the last non-zero value per ID in R? Example: Input: df <- data.frame(ID = c(1,1,1,1,1,1,1,2,2,2,2), Var1 = c(0,10, 30, 0, 0,50,80,0, 0, 57, 0)) Output: df <- data.frame(ID = c(1,1,1,1,1,1,1,2,2,2,2), Var1 = c(0,10, 30, 0, 0,50,80,0, 0, 57, 0), res = c(0,10,30,30,30,50,80,0,0,57,57)) Is there an easy way with lag function? 回答1: Here's a tidyverse approach: library(tidyverse) df %>% group_by(ID) %>% mutate(x = replace(Var1, cumsum(Var1 !=0) > 0 & Var1 == 0, NA))