I have a matrix:
mat <- matrix(c(0,0,0,0,1,1,1,1,-1,-1,-1,-1), ncol = 4 , nrow = 4)
and I apply the following functions to filter out the columns with only positive entries, but for the columns that have negative entries I get a NULL
. How can I suppress the NULL
s from the output of lapply
, apply
and 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 for any help.