[R] table over a matrix dimension...

Jonathan Greenberg jgrn at illinois.edu
Thu Jul 10 19:03:30 CEST 2014


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):

# Applying with the table() function doesn't work properly, because not all rows
# have ALL of the factors, so I get a list output:

# Hacked solution:
unique_values = letters[1:4]

countsmatrix <- t(apply(random_characters,1,function(x,unique_values)
for(i in seq(unique_values))
counts[i] = sum(x==unique_values[i])

# 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?


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
AIM: jgrn307, MSN: jgrn307 at hotmail.com, Gchat: jgrn307, Skype: jgrn3007

More information about the R-help mailing list