Re: [R] replace NULL with NA in matrix

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Thu, 17 Apr 2008 08:38:31 -0500

Tim Smith wrote:
> Hi,
>
> I had a matrix with NULL values, which I wanted to replace with NA. Is there an efficient way to do this?
>
> Small sample input matrix:
> A B C D E
> 1 5222.18 6355.10 4392.68 2607.41 4524.09
> 2 NULL 257.33 NULL 161.51 119.44
> 3 NULL 274.80 305.28 443.27 NULL
> 4 1759.76 1556.45 1224.06 1558.73 1837.09
>
>
> Tim

If you are reading this in from a text file, you can use:

  mat <- as.matrix(read.table(YourFileName, header = TRUE,

                   na.strings = "NULL"))

See the 'na.strings' argument in ?read.table

Note that by default, this will be read in as a data frame, not a matrix, so I added the extra coercion. The difference is quite important.

The above should yield:

 > mat

         A B C D E

1 5222.18 6355.10 4392.68 2607.41 4524.09
2      NA  257.33      NA  161.51  119.44
3      NA  274.80  305.28  443.27      NA
4 1759.76 1556.45 1224.06 1558.73 1837.09

 > str(mat)
  num [1:4, 1:5] 5222 NA NA 1760 6355 ...

HTH, Marc Schwartz



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 17 Apr 2008 - 14:10:25 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 17 Apr 2008 - 14:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive