Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert character(0) to NA in a list?

Tags:

list

r

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")
like image 613
Thaise Avatar asked Jun 26 '17 18:06

Thaise


People also ask

How to replace 0 to NA?

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.

How do I replace null with zero in R?

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.


2 Answers

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"
like image 105
Psidom Avatar answered Nov 11 '22 01:11

Psidom


a[a=="character(0)"] <- "NA"

Given your example this provides what you ask for, but is that actually what you want, though?

like image 4
Lyngbakr Avatar answered Nov 11 '22 00:11

Lyngbakr