0

Possible Duplicate:
Replace all 0 values to NA in R

Going off of this question. Is there a similar function in R such as x[is.na(x)] <- 0 except that it will changes every zero in a matrix to NA?

Community
  • 1
  • 1
pyCthon
  • 11,746
  • 20
  • 73
  • 135

1 Answers1

11

You can do it like this:

x[x == 0] <- NA

For example:

x = matrix(rep(0:1, 50), nrow=10)
x[x == 0] <- NA
print(x)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [2,]    1    1    1    1    1    1    1    1    1     1
# [3,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [4,]    1    1    1    1    1    1    1    1    1     1
# [5,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [6,]    1    1    1    1    1    1    1    1    1     1
# [7,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [8,]    1    1    1    1    1    1    1    1    1     1
# [9,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
#[10,]    1    1    1    1    1    1    1    1    1     1
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • What would the equivalent syntax be for a data.table object? – itpetersen Dec 07 '14 at 05:34
  • @dadrivr There's no particularly easy equivalent for a data.table. If the data.table is entirely numeric I'd recommend turning it into a matrix, doing this, and turning it back. If it includes factors you could try adapting [this solution](http://stackoverflow.com/questions/7235657/fastest-way-to-replace-nas-in-a-large-data-table), only in reverse – David Robinson Dec 07 '14 at 14:58