Rob Jensen Rob Jensen - 3 months ago 7
R Question

How can I print a matrix in R with NA values hidden?

I have a matrix that contains some

NA
elements (e.g.
mat
below), and I want to make a new function that prints it with the
NA
values hidden (i.e. as
fun
below). How can I achieve this?

mat <- cbind(c(1,2,NA,NA),c(3,3,3,NA),c(NA,4,4,4),c(NA,NA,5,5))
print(mat)

[,1] [,2] [,3] [,4]
[1,] 1 3 NA NA
[2,] 2 3 4 NA
[3,] NA 3 4 5
[4,] NA NA 4 5

fun(mat)

[,1] [,2] [,3] [,4]
[1,] 1 3
[2,] 2 3 4
[3,] 3 4 5
[4,] 4 5

Answer

We can use na.print in print

print(mat, na.print = "")
#      [,1] [,2] [,3] [,4]
#[1,]    1    3          
#[2,]    2    3    4     
#[3,]         3    4    5
#[4,]              4    5