如何用in R中的函数运行一个简单的for循环?

bq9c1y66  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(142)

在下面的数据集中,我想每隔72行计算一次函数decostand,这样做10次,下面是我的尝试。

library(vegan)
library(truncnorm)
df <- data.frame(set = rep(c(1:10), each = 72),
                 sp1 = rep(rtruncnorm(72, a=0, b=800, mean = 50, sd = 20), times = 10),
                 sp2 = rep(rtruncnorm(72, a=0, b=800, mean = 70, sd = 20), times = 10),
                 sp2 = rep(rtruncnorm(72, a=0, b=800, mean = 70, sd = 20), times = 10))

for(i in 1:unique(df$set)){
  df.hel <- decostand(df[i:i+71,2:4], method = "hellinger") 
   }

编辑:我删除了for循环的赋值语句。它仍然只计算1行。最终输出需要是720行。

n6lpvg4x

n6lpvg4x1#

我们可以通过“set”对列的子集进行split,循环遍历列表并应用decostand函数

out <- do.call(rbind, lapply(split(df[2:4], df$set), decostand, 
   method = "hellinger"))
row.names(out) <- NULL
> dim(out)
[1] 720   3

或者在for循环上

unq_se <- unique(df$set)
df.hel <- vector('list', length(unq_se))
names(df.hel) <- unq_se
for(nm in unq_se) {
   tmp <- subset(df, set == nm, select = 2:4)
    df.hel[[nm]] <- decostand(tmp,  method = "hellinger") 
}
df.hel_dat <- do.call(rbind, df.hel)

或使用dplyr

library(dplyr) # version >= 1.1.0
df %>%
  reframe(decostand(pick(everything()), method = "hellinger"), .by = "set") %>%
  as_tibble()
# A tibble: 720 × 4
     set   sp1   sp2 sp2.1
   <int> <dbl> <dbl> <dbl>
 1     1 0.496 0.628 0.599
 2     1 0.492 0.592 0.638
 3     1 0.518 0.641 0.566
 4     1 0.602 0.522 0.604
 5     1 0.328 0.695 0.640
 6     1 0.372 0.504 0.779
 7     1 0.416 0.585 0.696
 8     1 0.618 0.300 0.727
 9     1 0.497 0.692 0.523
10     1 0.552 0.578 0.601
# … with 710 more rows

相关问题