[R] Error in using nlevels in apply function

Sébastien pomchip at free.fr
Mon Aug 6 19:11:35 CEST 2007


Mike, Henrique,

Thanks for your help. Your code is doing the job perfectly.

Sébastien a écrit :
> 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.
>
>
>



More information about the R-help mailing list