Hi Dan: The reason that happens is because apply expects a matrix as input
so, since you sent in a dataframe ( which is really a list with each
component the same length ), apply converts the input dataframe to a matrix
but, when doing this, it needs to make conversions because a matrix needs
to be one type. ( that was a long sentence ).

So, you need to use lapply instead of apply. But when you use lapply you
need to unlist the output because lapply returns a list which causes havoc
when constructing the output dataframe. See contentsb below.

#=========================================================================

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)

contentsb<-function(x){
 output<-data.frame(Varnum=1:ncol(x),
 Name=names(x),
 Mode=unlist(lapply(x,mode)),
 Class=unlist(lapply(x,class)))
 print(output)
}

contentsb(data6)



On Thu, Dec 29, 2011 at 7:13 PM, Dan Abner <dan.abner99@gmail.com> wrote:

> 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)
> }
>
> ====
>
> 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]]

