r - apply, sapply and lappy return NULL -


i have matrix:

mat <- matrix(c(0,0,0,0,1,1,1,1,-1,-1,-1,-1), ncol = 4 , nrow = 4) 

and apply following functions filter out columns positive entries, columns have negative entries null. how can suppress nulls output of lapply, apply , sapply?

> lapply(as.data.frame(mat), function(x) { if( all(x >= 0) ){return(x)} }) $v1 [1] 0 0 0 0  $v2 [1] 1 1 1 1  $v3 null  $v4 [1] 0 0 0 0  > sapply(as.data.frame(mat), function(x) { if( all(x >= 0) ){return(x)} }) $v1 [1] 0 0 0 0  $v2 [1] 1 1 1 1  $v3 null  $v4 [1] 0 0 0 0   > apply(mat, 2, function(x){if (all(x >= 0)){return(x)}}) [[1]] [1] 0 0 0 0  [[2]] [1] 1 1 1 1  [[3]] null  [[4]] [1] 0 0 0 0 

thanks help.

how about

dd <- as.data.frame(mat) dd[sapply(dd,function(x) all(x>=0))] 

?

  • sapply(...) returns logical vector (in case true true false true) states whether columns have non-negative values.
  • when used data frame (not matrix), single-bracket indexing logical vector treats data frame list (which is) , creates list containing specified elements.

or alternatively

dd[apply(mat>=0,2,all)] 

in case use apply(...,2,...) on original matrix generate logical indexing vector.

or

mat[,apply(mat>=0,2,all)] 

in case since indexing matrix use [,logical_vector] select columns.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -