你就快到了。将代码包装在一个函数中,该函数只接受一个参数(list元素)。
customFunction <- function(x) {
Test <- x
null_models <- which(rownames(Test) == "NULL1" | rownames(Test) == "NULL2")
for (i in 1:nrow(Test)){
if (all(Test[null_models, 1]<=(Test[i,1]/2))) {
Test$Logical[i]<-"TRUE"
} else {
Test$Logical[i]<-"FALSE"
}}
Test
}
> lapply(mlist, FUN = customFunction)
[[1]]
matrix.1.4..nrow...4..ncol...1. Logical
NULL1 1 FALSE
NULL2 2 FALSE
ALT1 3 FALSE
ALT2 4 TRUE
[[2]]
matrix.8.11..nrow...4..ncol...1. Logical
NULL1 8 FALSE
NULL2 9 FALSE
ALT1 10 FALSE
ALT2 11 FALSE
[[3]]
matrix.0.3..nrow...4..ncol...1. Logical
NULL1 0 FALSE
NULL2 1 FALSE
ALT1 2 TRUE
ALT2 3 TRUE
下面是内环的一个简短变体:
for (i in 1:nrow(Test)) Test$Logical[i] <- all(Test[null_models,1]<=(Test[i,1]/2))
也可以用
apply()
-调用是可能的(即循环隐藏):
T0 <- Test[null_models,1]
Test$Logical <- apply(T0 <= matrix(Test[,1]/2, length(null_models), nrow(Test), byrow = TRUE), 2, all)
或
Test$Logical <- apply(sapply(Test[null_models,1], '<=', Test[,1]/2), 1, all)