dimanche 25 octobre 2020

tidyverse: completing mutate command [duplicate]

I want to replace a value with its lag (the value in the previous row) if the value is NA. I assumed that if there is more than one NA in succession, the first NA would be transformed to its lag value, and the next NA would be transformed to the new non-NA value in the previous row. However, only the first NA is transformed. Simplified example follows:

library(tidyverse)

t <- c('a' , NA , 'x' , NA , NA , 'z' , NA , NA , NA)  
u <- data.frame(t)
v <- mutate(u , t = ifelse(
  is.na(t) , lag(t) , t))  
v
#>      t
#> 1    a
#> 2    a
#> 3    x
#> 4    x
#> 5 <NA>
#> 6    z
#> 7    z
#> 8 <NA>
#> 9 <NA>

Created on 2020-10-25 by the reprex package (v0.3.0)

For example, I want row 5 to be x and rows 8 and 9 to be z. Note that in the real dataset, there can be several NAs in succession. How can I do this? Many thanks for any help!

Aucun commentaire:

Enregistrer un commentaire