Home > Software design >  replace NA values with sequence
replace NA values with sequence

Time:06-16

I am trying to fill in some NA values of a string but count the NA values that are being filled.

For example I have the following string:

string = c("A", "B", "C", NA, NA, "D", "E", NA, "F", "G", NA, NA)

Expected output:

"A", "B", "C", "NA_VALUE_1", "NA_VALUE_2", "D", "E", "NA_VALUE_3", "F", "G", "NA_VALUE_4", "NA_VALUE_5"

So, I want to paste the sequence paste("NA_VALUE_", valueHere) where valueHere increases.

CodePudding user response:

n_na = sum(is.na(string))
string[is.na(string)] <- paste0("NA_VALUE_", seq_len(n_na))

CodePudding user response:

You could try

ifelse(a <- is.na(string), paste0("NA_VALUE_", cumsum(a)), string)

# [1] "A"          "B"          "C"          "NA_VALUE_1" "NA_VALUE_2" "D"          "E"         
# [8] "NA_VALUE_3" "F"          "G"          "NA_VALUE_4" "NA_VALUE_5"

Because is.na(string) need to be used twice in this method, I store it as a new object a in the first part of ifelse() so that I can pass it into cumsum() afterward.

CodePudding user response:

Another possible solution, based on purrr::iwalk:

library(purrr)

iwalk(which(is.na(string)), ~ {string[.x] <<- paste0("NA_Value_", .y)})
string

#>  [1] "A"          "B"          "C"          "NA_Value_1" "NA_Value_2"
#>  [6] "D"          "E"          "NA_Value_3" "F"          "G"         
#> [11] "NA_Value_4" "NA_Value_5"
  •  Tags:  
  • r
  • Related