【发布时间】:2017-06-08 12:17:29
【问题描述】:
我不熟悉 R 中的循环,我需要帮助来编写多个嵌套循环。我有一个数据框,其中一行代表一个区域内一个站点的物种数量。有50个区域,区域之间的站点数量是不等的。对于每个区域,我需要根据逐渐增加的站点数量计算多样性指数,并为每个增量步骤复制这 1000 倍。例如:
R1 <- subset(df, region=="1") #this needs to be completed for all 50 regions
R1$region<-NULL
max<-nrow(R1)-1
iter <- 1000 #the number of iterations
n <- 1 # the number of rows to be sampled. This needs to increase until
“max”
outp <- rep(NA, iter)
for (i in 1:iter){
d <- sample(1:nrow(R1), size = n, replace=FALSE)
bootdata <- R1[d,]
x <- colSums(bootdata) #this is not applicable until n>1
outp[i] <- 1/diversity(x, index = "simpson")
}
这是一个示例数据集
structure(list(region = c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L), Sp1 = c(31L,
85L, 55L, 71L, 81L, 22L, 78L, 64L), Sp2 = c(10L, 84L, 32L, 86L,
47L, 93L, 55L, 35L), Sp3 = c(86L, 56L, 4L, 8L, 55L, 47L, 51L,
95L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-8L), .Names = c("region", "Sp1", "Sp2", "Sp3"), spec = structure(list(
cols = structure(list(region = structure(list(), class =
c("collector_integer",
"collector")), Sp1 = structure(list(), class = c("collector_integer",
"collector")), Sp2 = structure(list(), class = c("collector_integer",
"collector")), Sp3 = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("region", "Sp1", "Sp2", "Sp3")),
default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
简而言之,对于每个区域,我需要计算每个站点的“辛普森”指数,随机重采样 1000 次。然后,我需要在每列求和 1000 次后再次计算 2 个站点的索引。然后 3 个站点等,直到最大。
我也很难写输出。我希望每个区域都有一个数据框,其中的列代表 n 的 1000 次迭代,直到最大值。
在此先感谢
【问题讨论】:
-
请提供一个小的可重复数据集。 stackoverflow.com/questions/5963269/…
-
对不起,我真的很难弄清楚如何添加足够简洁的数据集以适应字符限制
-
@lmo 我已将其添加到原始帖子中。这是正确的格式,是吗?我基于stackoverflow.com/questions/5963269/…