简体   繁体   中英

How can I use loops in R

I am a new user of loops in R so Hopefully anyone helps me to dissolve that problem I have data. frame contains of 20 types of population as following

       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  

I need to calculate the mean and Variance of each population by using R column [ I want to dissolve that issue by using Loops in R] Thanks

No need to write loops, here are some methods

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

Or

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

Or

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

Or

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

Or

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

Or

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

If you insist to get a for loop solution, here goes

Predefining the result data set (because it is a bad practice growing objects within loops)

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

Running the loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM