[R] How to make a table of a desired dimension

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Fri Jun 8 19:49:59 CEST 2007


You need to basically use table on factors with fixed pre-specified 
levels. For example:

  x <- c(runif(100,10,40), runif(100,43,55))
  y <- c(runif(100,7,35),  runif(100,37,50))
  z <- c(runif(100,10,42), runif(100,45,52))
  xx <- ceiling(x);  yy <- ceiling(y);  zz <- ceiling(z)


  mylevels <- min( c(xx, yy, zz) ) : max( c(xx, yy, zz) )

  out <- cbind( table( factor(xx, levels=mylevels) ),
                table( factor(yy, levels=mylevels) ),
                table( factor(zz, levels=mylevels) ) )

You could replace the last command with simply

  sapply( list(xx, yy, zz),
                function(vec) table( factor(vec, levels=mylevels) ) )

Regards, Adai



Rubén Roa-Ureta wrote:
> Hi ComRades,
> 
> I want to make a matrix of frequencies from vectors of a continuous 
> variable spanning different values. For example this code
> x<-c(runif(100,10,40),runif(100,43,55))
> y<-c(runif(100,7,35),runif(100,37,50))
> z<-c(runif(100,10,42),runif(100,45,52))
> a<-table(ceiling(x))
> b<-table(ceiling(y))
> c<-table(ceiling(z))
> a
> b
> c
> 
> will give me three tables that start and end at different integer 
> values, and besides, they have 'holes' in between different integer 
> values. Is it possible to use 'table' to make these three tables have 
> the same dimensions, filling in the absent labels with zeroes? In the 
> example above, the desired tables should all start at 8 and tables 'a' 
> and 'c' should put a zero at labels '8' to '10', should all put zeros in 
> the frequencies of the labels corresponding to the holes, and should all 
> end at label '55'. The final purpose is the make a matrix and use 
> 'matplot' to plot all the frequencies in one plot, such as
> 
> #code valid only when 'a', 'b', and 'c' have the proper dimension
> p<-mat.or.vec(48,4)
> p[,1]<-8:55
> p[,2]<-c(matrix(a)[1:48])
> p[,3]<-c(matrix(b)[1:48])
> p[,4]<-c(matrix(c)[1:48])
> matplot(p)
> 
> I read the help about 'table' but I couldn't figure out if dnn, 
> deparse.level, or the other arguments could serve my purpose. Thanks for 
> your help
> Rubén
> 
> ______________________________________________
> 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