【发布时间】:2015-07-07 22:17:34
【问题描述】:
我有一个矩阵:
mat <- matrix(c(0,0,0,0,1,1,1,1,-1,-1,-1,-1), ncol = 4 , nrow = 4)
我应用以下函数过滤掉只有正条目的列,但对于有负条目的列,我得到一个NULL。如何从lapply、apply 和sapply 的输出中抑制NULLs?
> 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
感谢您的帮助。
【问题讨论】: