Replacing NA between two rows with the same values ​​in a specific column

I have a framework with multiple columns, and I want to replace NA in the same column if they are between two rows with the same number. Here are my details:

    v1 v2 
    1  2  
    NA 3
    NA 2
    1  1
    NA 7
    NA 2
    3  1

Basically, I want to start at the beginning of the data frame and replicate the NA in v1 column with the previous Non NA if the next Non NA matches the previous. That was said, I want the result to be like this:

    v1 v2 
    1  2  
    1 3
    1 2
    1  1
    NA 7
    NA 2
    3  1        

As you can see, lines 2 and 3 are replaced by the number “1” because lines 1 and 4 have the same number, but lines 5.6 remain unchanged because the non na values ​​in lines 4 and 7 are not identical. I played a lot, but so far no luck. Thanks

+4
source share
4 answers

zoo. NA NA , .

library(zoo)

ind1 <- na.locf(df$v1, fromLast = TRUE)
df$v1 <- na.locf(df$v1)
df$v1[df$v1 != ind1] <- NA

,

 v1 v2
1  1  2
2  1  3
3  1  2
4  1  1
5 NA  7
6 NA  2
7  3  1
+4

R-, , Sotos one:

replace_na <- function(x){
    f <- function(x) ave(x, cumsum(!is.na(x)), FUN = function(x) x[1])
    y <- f(x)
    yp <- rev(f(rev(x)))
    ifelse(!is.na(y) & y == yp, y, x)
}
df$v1 <- replace_na(df$v1)

:

> replace_na(c(1, NA, NA, 1, NA, NA, 3))
[1]  1  1  1  1 NA NA  3
+1

tidyverse fill

library(tidyverse)
df1 %>%
  mutate(vNew = v1) %>%
  fill(vNew, .direction = 'up') %>%
  fill(v1)  %>%
  mutate(v1 = replace(v1, v1 != vNew, NA)) %>%
  select(-vNew)
#  v1 v2
#1  1  2
#2  1  3
#3  1  2
#4  1  1
#5 NA  7
#6 NA  2
#7  3  1
+1

I could use the na.locf function for this. Basically, I use the usual na.locf package function package to replace each NA with the last previous non NA and store the data in a column. using the same function, but fixing fromlast = TRUE NA replaces the first next nonNA and saves them in a different column. I checked these two columns, and if the results in each row for these two columns do not match, I replace them with NA.

0
source

Source: https://habr.com/ru/post/1684127/


All Articles