如何在R中使用循环

时间:2014-11-04 18:08:41

标签: r

我是R中循环的新用户,所以希望有人帮助我解决这个问题 我有数据。框架包含20种类型的人口如下

       Sample  Population       R               
1 Bari1_062-1      Bari1       94.52303  
2 Bari1_062-2      Bari1       98.27683   
3 Bari1_062-3      Bari1      100.53170   
4 Bari1_062-4      Bari1       96.65940   
5 Bari1_062-5      Bari1     117.62474  
6 Bari1_063-1      Bari1      144.39547  

我需要使用R列来计算每个种群的平均值和方差[我想通过在R中使用循环解决该问题] 感谢

1 个答案:

答案 0 :(得分:3)

无需编写循环,这里有一些方法

with(df, tapply(R, Population, function(x) c(mean(x), var(x))))

或者

aggregate(R ~ Population, df,  function(x) c(mean(x), var(x)))

或者

do.call(rbind, by(df, df$Population, function(x) c(mean(x$R), var(x$R))))

或者

do.call(rbind, lapply(split(df, df$Population), function(x) c(mean(x$R), var(x$R))))

或者

library(data.table)
setDT(df)[, list(Var = var(R), Mean = mean(R)), by = Population]

或者

library(dplyr)
df %>%
  group_by(Population) %>%
  summarise(Var = var(R), Mean = mean(R))

如果你坚持要获得for循环解决方案,那么

预定义结果数据集(因为在循环中增长对象是一种不好的做法)

Res <- data.frame(Population = unique(df$Population),
                  Mean = rep(NA, length(unique(df$Population))),
                  Var = rep(NA, length(unique(df$Population))))

运行循环

for(i in unique(df$Population)){
  Res$Mean[Res$Population == i] <- mean(df$R[df$Population == i]) 
  Res$Var[Res$Population == i] <- var(df$R[df$Population == i]) 
}
Res
#   Population     Mean      Var
# 1      Bari1 108.6685 375.0275