Pecade Pecade - 3 months ago 17
R Question

Delete the rows of matrix with Inf

I have three lists with Inf as a numeric and "NaN" as a character variable.

v1<-list(1,Inf,3,4,5,6,"NaN")
v2<-list(1,"NaN",3,4,5,6,5)
v3<-list(1,2,3,4,5,6,"NaN")


for the moment I can make a matrix with cbind, but the desired result is the code B).

A) What I got:

matrix<-cbind(v1,v2,v3)
v1 v2 v3
[1,] 1 1 1
[2,] Inf "NaN" 2
[3,] 3 3 3
[4,] 4 4 4
[5,] 5 Inf 5
[6,] 6 6 6
[7,]"NaN" 7 "NaN"


B) I want to get:

v1 v2 v3
[1,] 1 1 1
[2,] 3 3 3
[3,] 4 4 4
[4,] 6 6 6


Context:
I wanted to export into a .txt file some results located in 3 lists, the easy for me was to use cbind to get a matrix and use

write.table(matrix, file="mymatrix.txt", row.names=FALSE, col.names=FALSE)

Answer

Couple of suggestions regarding the problem.

1) It is better not to name a matrix object as matrix.

2) NaN or NA have a special meaning and are not character strings. By using quotes "NaN", it becomes difficult to apply the custom functions is.nan/is.na to do any manipulations. So, we have to resort to ==/!=

3) It is not clear why the individual list are cbinded to a matrix.


Based on the input data, we can loop through the columns of 'matrix' with apply, then loop through each of the list elements, check whether we have a finite element and is not a "NaN", get the rowSums, negate (! - converts the 0 elements to TRUE i.e. all the elements in the row are finite and all other values to FALSE). Use the logical index to subset the rows.

 matrix[!rowSums(apply(matrix, 2, FUN = function(x) 
         sapply(x, function(y) !(is.finite(y) & y !="NaN")))),]
 #    v1 v2 v3
 #[1,] 1  1  1 
 #[2,] 3  3  3 
 #[3,] 4  4  4 
 #[4,] 6  6  6