[R] Mean not working in function

arun smartpink111 at yahoo.com
Fri Apr 11 18:47:53 CEST 2014


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