[R] Creating frequency table using conditions in a for-loop

Jim Lemon jim at bitwrit.com.au
Thu Jun 7 10:30:52 CEST 2012


On 06/07/2012 08:08 AM, Faz Jones wrote:
> Hi,
>
> I have attached a word document to explain the problem i am having
> creating a for-loop in R with conditions to create a frequency table.
> I am new to R so any help would be greatly appreciated.
>
Hi Jones,
Unfortunately, you might as well have attached a popsicle to a camel and 
sent it across the Sahara. Just to show you that this help list really 
is helpful, I'm going to try to read your mind. You want to create a 
frequency table by counting the values in some set of observations. 
Maybe it's homework. Heck, anybody who tries to send a Word document to 
the R help list is more to be pitied than censured.

# get a bunch of observations
mydata<-sample(LETTERS[1:6],50,TRUE)
# let's pretend that we don't know how many different letters there are
allletters<-sort(unique(mydata))
# now create something to hold your answer
myanswer<-rep(0,length(allletters))
# give it some names, you'll need them later
names(myanswer)<-allletters
# okay, here we go round the loop
for(i in 1:length(mydata)) {
  answerindex<-which(allletters %in% mydata[i])
  myanswer[answerindex]<-myanswer[answerindex]+1
}
print(myanswer)
table(mydata)

Feel better now?

Jim



More information about the R-help mailing list