Home > other >  Compute variance of a data frame using a for-loop in R?
Compute variance of a data frame using a for-loop in R?

Time:06-06

How can I compute the variance of every column of a data frame with different classes using a for-loop? The df has all four types of classes/types of columns. I would like to tell it to print the variance for the possible ones and print "no variance" for the not possible ones i.e. != "numeric" | "integer"

for(i in df) {
   if(class (i) == "numeric" | class(i) == "integer") 
      print(variance(df.column))
   else:
      print("no variance")
}

I'm only getting printed "no variance" with this for-loop.

CodePudding user response:

Using iris dataset as an example -

for(i in seq_along(iris)) {
  tmp <- iris[[i]]
  if(class(tmp) %in%  c("numeric", "integer"))  
    print(var(tmp))
  else print("no variance")
}

#[1] 0.6856935
#[1] 0.1899794
#[1] 3.116278
#[1] 0.5810063
#[1] "no variance"
  • Related