如何编写重新取样并增加样本大小的嵌套循环

时间:2017-06-08 12:17:30

标签: r loops nested

我是R中的循环新手,我需要帮助编写多个嵌套循环。我有一个数据框,其中一行代表一个地区内一个地点的物种数量。有50个地区,地区之间的地点数量不平等。对于每个区域,我需要根据递增的站点数量计算多样性指数,并为每个增量步骤复制1000x。例如:

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"))

简而言之,对于每个区域,我需要为每个站点计算“simpson”索引,随机重新采样1000次。然后,我需要在每列累加1000次之后再为2个站点计算索引。然后是3个站点等,直到最大

我也在努力编写输出。我希望每个区域都有一个数据框,其中的列代表1000次迭代,直到最大值

非常感谢提前

1 个答案:

答案 0 :(得分:0)

您可以一次编写一个适用于通用区域的函数。然后,按区域将数据拆分为列表,并使用sapply将自定义函数应用于每个列表元素。

bootstrapByRegion <- function(R) {
  rgn <- unique(R$region)
  message(sprintf("Processing %s", rgn))
  R$region <- NULL

  nmax <- nrow(R)-1

  if (nmax == 0) stop(sprintf("Trying to work on one row. No dice. Manually exclude region %s or handle otherwise.", rgn))

  iter <- 1000 #the number of iterations
  # pre-allocate the result
  output <- matrix(NA, nrow = iter, ncol = nmax)

  for (i in 1:nmax) {
    i <- 1
    output[, i] <- replicate(iter, expr = {
      d <- sample(1:nrow(R), size = i, replace=FALSE)
      bootdata <- R[d, , drop = FALSE]
      x <- colSums(bootdata) #this is not applicable until n>1
      outp <- 1/diversity(x, index = "simpson")
      outp
    })
  }
  output
}

xy <- split(df, f = df$region)
result <- sapply(xy, FUN = bootstrapByRegion) # list element is taken as R

由于区域3只有一行,因此无效(因为nrow(R)-1)。您可以通过多种方式排除这些区域。这是一个。

result <- sapply(xy[sapply(xy, nrow) > 1], FUN = bootstrapByRegion)