Cau*_*chy 10 r apply lapply sapply
我有一个矩阵:
mat <- matrix(c(0,0,0,0,1,1,1,1,-1,-1,-1,-1), ncol = 4 , nrow = 4)
Run Code Online (Sandbox Code Playgroud)
并且我应用以下函数来过滤掉只有正条目的列,但是对于具有负条目的列,我得到了一个NULL
.如何NULL
从输出中抑制s 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
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
怎么样
dd <- as.data.frame(mat)
dd[sapply(dd,function(x) all(x>=0))]
Run Code Online (Sandbox Code Playgroud)
?
sapply(...)
返回一个逻辑向量(在本例中TRUE TRUE FALSE TRUE
),指出列是否具有所有非负值.或者
dd[apply(mat>=0,2,all)]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们apply(...,2,...)
在原始矩阵上使用以生成逻辑索引向量.
要么
mat[,apply(mat>=0,2,all)]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,因为我们正在索引矩阵,我们[,logical_vector]
用来选择列.
另一种选择是Filter
你的结果,而Negate
荷兰国际集团NULL
秒(如果你想保持在一个列表格式)
Res <- lapply(as.data.frame(mat), function(x) if(all(x >= 0)) x)
Filter(Negate(is.null), Res)
# $V1
# [1] 0 0 0 0
#
# $V2
# [1] 1 1 1 1
#
# $V4
# [1] 0 0 0 0
Run Code Online (Sandbox Code Playgroud)