我试图多次重新采样(替换)一个data.frame。该数据框是按场地矩阵的物种。此数据中有几个零,这意味着重采样过程有时只产生零行。因此,我想从每个for循环中消除只有零行的矩阵,因为函数multipart(vegan package)不接受这些矩阵。
提前谢谢大家。
require(vegan)
# DATA (Edited)
dat <- read.table("df.stack.txt", h=T) # Link above
mat <- dat[,c(-1, -2, -3)]
levels <- dat[,1:3]
## Vectors for saving desired statistics
alfa.null <- NULL
beta1.null <- NULL
beta2.null <- NULL
## Shuffling matrices ## Here is the problem
times <- 99
for (i in times) {
mat.rand <- sample(mat, replace=TRUE) ### Problem to be solved - some matrices will have only zero rows
div.aleat <- multipart(mat.rand ~ ., levels, index="renyi", scales=1, nsimul=99, global=TRUE)
alfa.null[i] <- div.aleat$statistic[[1]]
beta1.null[i] <- div.aleat$statistic[[4]]
beta2.null[i] <- div.aleat$statistic[[5]]
}
答案 0 :(得分:0)
你需要保持重新采样,直到得到如此的非零矩阵:
times <- 99
for (i in seq.int(times)) {
while(TRUE){
mat.rand <- sample(df, replace=TRUE) ### Problem to be solved - some matrices will have only zero rows
if(any(rowSums(mat.rand)!=0))
break
}
blah blah blah
}
当然使用while(TRUE)
循环,抓住无限循环是个好主意:
times <- 99
max_Tries <- 100
for (i in seq.int(times)) {
tries = 0
while(TRUE){
mat.rand <- sample(df, replace=TRUE) ### Problem to be solved - some matrices will have only zero rows
if(any(rowSums(mat.rand)!=0))
break
tries <- tries + 1
if(tries > max_Tries)
stop("number of tries exceeded max_Tries: possible infinite loop")
}
blah blah blah
}