[R] Error in using nlevels in apply function

Mike Meredith mmeredith at wcs.org
Mon Aug 6 18:52:50 CEST 2007



apply(mydata,2,nelem,... passes the columns of mydata _one_by_one_ to nelem,
so nelem only sees a vector, and complains if it's expecting a 2d object.

Try this:

nelem<-function(x) nlevels(factor(x)) 
apply(mydata[,mycol.index],2,nelem) 

HTH, Mike.


Sébastien-18 wrote:
> 
> Dear R users,
> 
> I am currently trying to create my first personnal function and use it 
> with the apply function. The purpose of this function is to create a 
> vector summarizing the number of levels in a given selection of 
> data.frame columns.
> I tried to transpose the indexation method used by the nlevels function 
> but it doesn't seem to work. I did not find anything uesful in the 
> archives so could someone point to me where my mistake(s) is (are) ?
> 
> Thanks in advance
> 
> Sebastien
> 
> #-------------------------
> 
> mydata<-data.frame(1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6,1:6)
> mycol.index<-c(1,5,3)
> 
> nelem<-function(x,col.id) nlevels(factor(x[,col.id]))
> my.nlevels.col<-apply(mydata,2,nelem,mycol.index)
> my.nlevels.col
> 
> #----------------------------
> 
> #The error message is the following
> #>Error in x[, col.id] : incorrect number of dimensions
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/Error-in-using-nlevels-in-apply-function-tf4225090.html#a12019950
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list