Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NA/NaN/Inf in a matrix

Tags:

r

na

matrix

rows

I want to try two things :

  1. How do I remove rows that contain NA/NaN/Inf
  2. How do I set value of data point from NA/NaN/Inf to 0.

So far, I have tried using the following for NA values, but been getting warnings.

> eg <- data[rowSums(is.na(data)) == 0,]
 Error in rowSums(is.na(data)) : 
       'x' must be an array of at least two dimensions
     In addition: Warning message:
     In is.na(data) : is.na() applied to non-(list or vector) of type 'closure'
like image 747
user2199881 Avatar asked Apr 02 '13 19:04

user2199881


1 Answers

I guess I'll throw my hat into the ring with my preferred methods:

# sample data
m <- matrix(c(1,2,NA,NaN,1,Inf,-1,1,9,3),5)
# remove all rows with non-finite values
m[!rowSums(!is.finite(m)),]
# replace all non-finite values with 0
m[!is.finite(m)] <- 0
like image 62
Joshua Ulrich Avatar answered Sep 21 '22 08:09

Joshua Ulrich