How can character(0)
be converted to NA
in a list?
Example:
a = list("a", character(0), "b", "c")
to
a = list("a", NA, "b", "c")
Replace 0 with NA in an R DataframeUse df[df==0] to check if the value of a dataframe column is 0, if it is 0 you can assign the value NA . The below example replaces all 0 values on all columns with NA.
Replace NA with 0 in R Data Frame To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.
Replace character(0)
only (assume you meant character(0)
instead of "character(0)"
):
a = list("a", character(0), "b", "c")
lapply(a, function(x) if(identical(x, character(0))) NA_character_ else x)
#[[1]]
#[1] "a"
#[[2]]
#[1] NA
#[[3]]
#[1] "b"
#[[4]]
#[1] "c"
Replace all length-0 elements:
a[lengths(a) == 0] <- NA_character_
a
#[[1]]
#[1] "a"
#[[2]]
#[1] NA
#[[3]]
#[1] "b"
#[[4]]
#[1] "c"
a[a=="character(0)"] <- "NA"
Given your example this provides what you ask for, but is that actually what you want, though?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With