there is also colwise in the plyr package. > library(plyr) > colwise(class)(data6) v13 v14 v15 f4 v16 1 integer numeric character factor logical
Justin On Thu, Dec 29, 2011 at 4:47 PM, Jean V Adams <jvad...@usgs.gov> wrote: > Dan Abner wrote on 12/29/2011 06:13:11 PM: > > > Hi everyone, > > > > I am attempting to use the apply() function to obtain the mode and class > of > > each column in a data frame, however, I am encountering unexpected > results. > > I have the following example data: > > > > > > v13<-1:6 > > v14<-c(1,2,3,3,NA,1) > > v15<-c("Good","Bad",NA,"Good","Bad","Bad") > > f4<-factor(rep(c("Blue","Red","Green"),2)) > > v16<-c(F,T,F,F,T,F) > > data6<-data.frame(v13,v14,v15,f4,v16) > > data6 > > > > > > Here is my function definition: > > > > > > contents<-function(x){ > > output<-data.frame(Varnum=1:ncol(x), > > Name=names(x), > > Mode=apply(x,2,mode), > > Class=apply(x,2,class)) > > print(output) > > } > > > Use sapply() instead of apply(). In the help file for apply() it says: " > If X is not an array but an object of a class with a non-null dim value > (such as a data frame), apply attempts to coerce it to an array via > as.matrix if it is two-dimensional (e.g., a data frame) or via as.array." > This coercion to a matrix might be causing the unexpected result. sapply() > and lapply() are designed specifically for lists (which a data frame is). > I also simplified the function a bit ... > > contents<-function(x){ > data.frame(Varnum=1:ncol(x), Name=names(x), > Mode=sapply(x,mode), Class=sapply(x,class)) > } > > Jean > > > > ==== > > > > When I call the function, I obtain the following: > > > > > > > contents(data6) > > Varnum Name Mode Class > > v13 1 v13 character character > > v14 2 v14 character character > > v15 3 v15 character character > > f4 4 f4 character character > > v16 5 v16 character character > > > > ===== > > > > Any help is appreciated. > > > > Thank you, > > > > Dan > > > > [[alternative HTML version deleted]] > > > > ______________________________________________ > > R-help@r-project.org mailing list > > https://stat.ethz.ch/mailman/listinfo/r-help > > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > > and provide commented, minimal, self-contained, reproducible code. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.