[R] Mean not working in function

arun smartpink111 at yahoo.com
Wed Apr 16 19:03:50 CEST 2014


Hi,
Try:
set.seed(48)
dat1 <- data.frame(matrix(sample(c(NA, 1:20), 4 * 20, replace = TRUE), ncol = 4),  fac1 = sample(LETTERS, 20, replace = TRUE)) mysummary <- function(dataf) { indx <- sapply(dataf, is.numeric) for (name in names(dataf)[indx]) { cat("Variable name: ", name, ": Mean=", mean(dataf[, name], na.rm = TRUE),  "\n") }
} mysummary2 <- function(dataf) { indx <- sapply(dataf, is.numeric) cat(paste(paste("Variable name: ", names(dataf)[indx], ": Mean=", format(colMeans(dataf[,  indx], na.rm = TRUE), digits = 7), collapse = "\n"), "\n"))
} 

A.K.



Thanks for the reply.
How can I avoid getting factor variables in this loop. I think I need to use dataf[sapply(df2, is.numeric)], but I am not able to combine it with: mean(dataf[,name],na.rm=TRUE). 


On Friday, April 11, 2014 12:47 PM, arun <smartpink111 at yahoo.com> wrote:
Hi,
Try:
mysummary <- function(dataf){ for(name in names(dataf)){ cat ("Variable name: ", name, ": Mean=", mean(dataf[,name],na.rm=TRUE),"\n") }
} 

##Using some example data:

set.seed(48)
dat1 <- as.data.frame(matrix(sample(c(NA,1:20),4*20,replace=TRUE),ncol=4)) mysummary(dat1)
#Variable name:  V1 : Mean= 11.64706
#Variable name:  V2 : Mean= 10.88889
#Variable name:  V3 : Mean= 12.35 

#Variable name:  V4 : Mean= 10.52632 


#Another way would be:

mysummary2 <- function(dataf){ cat(paste(paste("Variable name: ", names(dataf), ": Mean=", format(colMeans(dataf,na.rm=TRUE),digits=7),collapse="\n"),"\n"))
}
mysummary2(dat1) 

#Variable name:  V1 : Mean= 11.64706
#Variable name:  V2 : Mean= 10.88889
#Variable name:  V3 : Mean= 12.35000
#Variable name:  V4 : Mean= 10.52632 


A.K.


I am trying following function: mysummary <- function(dataf){ for(name in names(dataf)){ cat ("Variable name: ", name, ": Mean=", mean(name),"\n") }
} The variable name is properly picked up but the mean is shows as NA. The command warnings() show:
In mean.default(name) : argument is not numeric or logical: returning NA




More information about the R-help mailing list