我的问题包含两个部分。
假设我有两个矩阵:
> mat1
[,1] [,2] [,3] [,4] [,5]
[1,] 0.0 0.0 0.0 0.0 0
[2,] 0.5 0.0 0.0 0.0 0
[3,] 0.4 0.5 0.0 0.0 0
[4,] 0.5 0.5 0.4 0.0 0
[5,] 0.5 0.5 0.4 0.7 0
> mat2
[,1] [,2] [,3] [,4] [,5]
[1,] 0.0 0.0 0.0 0.0 0
[2,] 0.5 0.0 0.0 0.0 0
[3,] 0.9 0.5 0.0 0.0 0
[4,] 0.5 0.5 0.4 0.0 0
[5,] 0.5 0.5 0.4 0.3 0
> mat <- list(mat1, mat2)
我想检查两个矩阵中的每个对应值是否为1
的总和。如果是,则打印总和,否则返回错误。这是我的尝试:
mat <- list(mat1, mat2)
myf <- function(mat){
for(i in 1:5){
for(j in 1:5){
if(all(Reduce('+', mat)) == 1 ){
return(Reduce('+', mat))
}else{
stop("some of output are > 1")
}
}
}
} 输出:
Error in myf(family) : cann
In addition: Warning message:
In all(Reduce("+", mat)) : coercing argument of type 'double' to logical
我想检查矩阵的任何元素是否为< 0
。
我试过了:
if(Reduce('|', lapply(family, '<', 0))){
停止(&#34;停止所有金额必须是正数&#34;) }
输出结果为:
Warning message:
In if (Reduce("|", lapply(family, "<", 0))) { :
the condition has length > 1 and only the first element will be used
请帮忙吗?
答案 0 :(得分:0)
感谢@akrun和@tobiasegli_te
myf <- function(mat){
if(!all(Reduce('+', mat) <= 1 )){
stop("some of output are > 1")
}
}
if(all(Reduce('|', lapply(mat, '<', 0)))){
stop("stop all sum must be positive")
}