Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

replace - R replacing zeros in dataframe with next non zero value

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

How can I replace the zero values with the last non zero value ie column df$b to be:

 1,-1,-1,-1,-1,-1,-1,1,1,1

Thank you for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...