Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NA with empty string in a list

Tags:

r

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.

like image 696
Maximilian Avatar asked Mar 07 '26 03:03

Maximilian


1 Answers

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"  ""  
like image 104
josliber Avatar answered Mar 09 '26 17:03

josliber