Gunnerfan
Gunnerfan

Reputation: 123

For loop for to show mean for multiple variables in R

Everything in this code works but when it comes to finding the mean for all the variables with this part mean(df3[[i]]) it shows only one mean and not the other 16 mean values. Using a for loop does nothing either

for(i in 1:17){ mean(df3[[i]]) }

Can someone explain how to rectify this?

setwd("C:/Users/A/Desktop/ResearchData")
library (circular)
df<- read.csv("Direction.csv", header = TRUE)
df1 <- df [ which(df$Month==1 & df$Day>0 & df$Day <32) ,]
df2 <- df1[c(-1,-2,-3)]
df3<- lapply(df2, function(df2) circular(df2, units='degrees', template='geographics'))
dens<- lapply(df3, density.circular, bw =20)

par(mfrow=c(5,4), oma=c(2,1.3,2,2), mar=c(1.5,2,2,1), tcl=-0.2, mgp=c(0,1,0))
cl = c("lightblue", "red", "lightgreen", "orange2", "seashell4", "sienna", "olivedrab",
       "darkkhaki", "yellow3", "bisque2", "cornflowerblue", "magenta", 
       "black", "brown", "forest green", "navy", "burlywood4")
titles <- c("1000mb", "925mb", "850mb", "700mb", "600mb", "500mb", "400mb", "300mb", 
            "250mb", "200mb", "150mb", "100mb","70mb", "50mb", "30mb", "20mb", "10mb")
for(i in 1:17){
  plot(dens[[i]], main = titles[i], col = cl[i])     
}
title ("Probability Density Function of Height Over 30 Years for January", outer = TRUE) 

mean(df3[[i]])


par(mfrow=c(5,4), oma=c(2,1.3,2,2), mar=c(1.5,2,2,1), tcl=-0.2, mgp=c(0,1,0))
titles <- c("1000mb", "925mb", "850mb", "700mb", "600mb", "500mb", "400mb", "300mb", 
            "250mb", "200mb", "150mb", "100mb","70mb", "50mb", "30mb", "20mb", "10mb")
for(i in 1:17){
  plot(mean(df3[[i]]), main = titles[i],)  

Upvotes: 0

Views: 223

Answers (1)

kilojoules
kilojoules

Reputation: 10093

the mean statement should be within the for loop

for(i in 1:17){
  plot(dens[[i]], main = titles[i], col = cl[i]) 
  print(mean(df3[[i]]))
}
title ("Probability Density Function of Height Over 30 Years for January", outer = TRUE) 

Upvotes: 1

Related Questions