Christopher Flach Christopher Flach - 18 days ago 7
R Question

R For Loops Column Means

Updated based on responses. Added reproducible data. Unfortunately, I have to do a For Loop within a For Loop.

I need to do a for loop within a for loop to determine the column means. The outer for loop is to determine which columns are numeric. The inner for loop calculates the means for each column (while excluding NAs). I think I have the outer loop down. I just can't seem to figure out how to do the inner loop with the approach I'm taking. Any help is greatly appreciated.

a <- c('Ned', 'Rod', 'Todd')
b <- c(60, 10, 8)
c <- c(190, 80, 60)
Flanders <- data.frame(Name=a, Age=b, Weight=c)

numericvars <- NULL
for (m in names(Flanders)){
if(class(Flanders[,m]) == 'integer' | class(Flanders[,m]) == 'numeric'){
numericvars[m] <- mean(Flanders[,m],na.rm = TRUE)
}
}

Answer

Here is some very strange but working (and does work) function using a loop within a loop. Hopefully it can be of some help. Note that the integer is something like a subclass of numeric.

numericvars <- NULL
flanders.mean <- NULL
for (m in names(Flanders)){
  if(is.numeric(Flanders[, m])){
    numericvars <- c(numericvars, m)
  }
  for (k in numericvars) {
    flanders.mean[m] <- sum(Flanders[, m])/nrow(Flanders)
  }
}

flanders.mean 
   Age Weight 
    26    110
Comments