stu
stu

Reputation: 183

Omitting NA/NaN from Matrix

I'm trying to output the rows of a matrix but I want to omit NaN and NAs. The following simple example illustrates:

 m <- matrix(c(1,2,NA,NaN,1,-1,-1,1,9,3),5)
for (i in 1:nrow(m)) { 
  cat(paste(sprintf('%d:%f', 1:ncol(m), m[i, ]), collapse=' '), "\n") 
 }

and the output is this:

1:1.000000 2:-1.000000 
1:2.000000 2:-1.000000 
1:NA 2:1.000000 
1:NaN 2:9.000000 
1:1.000000 2:3.000000 

but I want:

1:1.000000 2:-1.000000 
1:2.000000 2:-1.000000 
2:1.000000 
2:9.000000 
1:1.000000 2:3.000000 

I've been trying various combinations of !is.na but no joy. Can anyone help?

Upvotes: 0

Views: 60

Answers (2)

jrdnmdhl
jrdnmdhl

Reputation: 1955

m <- matrix(c(1,2,NA,NaN,1,-1,-1,1,9,3),5)
for (i in 1:nrow(m)) { 
  row <- m[i,]
  row <- row[!is.na(row)]
  cat(paste(sprintf('%d:%f', 1:length(row), row), collapse=' '), "\n") 
}

Here is a solution using is.na().

Output:

1:1.000000 2:-1.000000 
1:2.000000 2:-1.000000 
1:1.000000 
1:9.000000 
1:1.000000 2:3.000000 

Upvotes: 0

DaveTurek
DaveTurek

Reputation: 1297

You can use is.finite

 m <- matrix(c(1,2,NA,NaN,1,-1,-1,1,9,3),5)
f <- apply(m,1,function(x) sum(is.finite(x))) #how many finite in each row
for (i in 1:nrow(m)) {
cat(paste(sprintf('%d:%f', 1:f[i], m[i, ][is.finite(m[i,])]), collapse=' '), "\n")  
}

Upvotes: 1

Related Questions