R replacing zeros in dataframe with next non zero value

后端 未结 1 1375
难免孤独
难免孤独 2020-12-11 19:07

I have a dataframe with a column containing zero values:

a <- 1:10
b <- c(1, 0, 0, 0, 0, -1, -1, 0, 0, 1)
df <- data.frame(a, b)
df
<
相关标签:
1条回答
  • 2020-12-11 19:49

    Here's one way with na.locf from zoo. Although this method does change some values to NA in the process, the code is nice and painless.

    library(zoo)
    na.locf(with(df, ifelse(b == 0, NA_real_, b)), fromLast = TRUE)
    # [1]  1 -1 -1 -1 -1 -1 -1  1  1  1
    

    An alternative to this, and one that might be faster than ifelse on long vectors, is

    na.locf(with(df, { is.na(b) <- b == 0; b }), fromLast = TRUE)
    # [1]  1 -1 -1 -1 -1 -1 -1  1  1  1
    
    0 讨论(0)
提交回复
热议问题