Maximilian
Maximilian

Reputation: 4229

Replace NA with empty string in a list

I have large list of matrix data that looks like this:

$`1`
 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]                     
 2010 "6 811 529 000" NA   NA   NA   "455 782 000"  
 2011 "7 531 264 000" NA   NA   NA   "585 609 000"        
 2012 "8 013 843 000" NA   NA   NA   "702 256 000" 

and I would like to replace the NA with empty string like this : ""

The solution must be without conversion to data.frame since this: x[is.na(x)] <- "" would solve the issue.

This works for me: print(x, na.print = "") but I cannot figure it out how to store the print output.

Upvotes: 3

Views: 2998

Answers (1)

josliber
josliber

Reputation: 44340

You can do this with lapply:

# Setup sample data frame
dat = list(matrix(c(NA, "a", "b", NA), nrow=2),
           matrix(c(rep("r", 8), NA), nrow=3))
dat
# [[1]]
#      [,1] [,2]
# [1,] NA   "b" 
# [2,] "a"  NA  
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,] "r"  "r"  "r" 
# [2,] "r"  "r"  "r" 
# [3,] "r"  "r"  NA  

# Do conversion
dat <- lapply(dat, function(x) { x[is.na(x)] <- "" ; x })
dat
# [[1]]
#      [,1] [,2]
# [1,] ""   "b" 
# [2,] "a"  ""  
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,] "r"  "r"  "r" 
# [2,] "r"  "r"  "r" 
# [3,] "r"  "r"  ""  

Upvotes: 3

Related Questions