[R] table over a matrix dimension...
Jonathan Greenberg
jgrn at illinois.edu
Thu Jul 10 19:03:30 CEST 2014
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: jgrn307 at hotmail.com, Gchat: jgrn307, Skype: jgrn3007
More information about the R-help
mailing list