You can make make a factor with a common set of levels out of each slice of the matrix so all the tables are the same size:
f <- function (charMatrix, levels = unique(sort(as.vector(charMatrix)))) { apply(charMatrix, 1, function(x) table(factor(x, levels = levels))) } used as > m <- cbind(c("A","A","A"), c("B", "A", "A")) > f(m) [,1] [,2] [,3] A 1 2 2 B 1 0 0 Bill Dunlap TIBCO Software wdunlap tibco.com On Thu, Jul 10, 2014 at 10:03 AM, Jonathan Greenberg <j...@illinois.edu> wrote: > R-helpers: > > I'm trying to determine the frequency of characters for a matrix > applied to a single dimension, and generate a matrix as an output. > I've come up with a solution, but it appears inelegant -- I was > wondering if there is an easier way to accomplish this task: > > # Create a matrix of "factors" (characters): > random_characters=matrix(sample(letters[1:4],1000,replace=TRUE),100,10) > > # Applying with the table() function doesn't work properly, because not > all rows > # have ALL of the factors, so I get a list output: > apply(random_characters,1,table) > > # Hacked solution: > unique_values = letters[1:4] > > countsmatrix <- t(apply(random_characters,1,function(x,unique_values) > { > counts=vector(length=length(unique_values)) > for(i in seq(unique_values)) > { > counts[i] = sum(x==unique_values[i]) > } > return(counts) > }, > unique_values=unique_values > )) > > # Gets me the output I want but requires two nested loops (apply and > for() ), so > # not efficient for very large datasets. > > ### > > Is there a more elegant solution to this? > > --j > > -- > Jonathan A. Greenberg, PhD > Assistant Professor > Global Environmental Analysis and Remote Sensing (GEARS) Laboratory > Department of Geography and Geographic Information Science > University of Illinois at Urbana-Champaign > 259 Computing Applications Building, MC-150 > 605 East Springfield Avenue > Champaign, IL 61820-6371 > Phone: 217-300-1924 > http://www.geog.illinois.edu/~jgrn/ > AIM: jgrn307, MSN: jgrn...@hotmail.com, Gchat: jgrn307, Skype: jgrn3007 > > ______________________________________________ > 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.