[R] trying to get rid of for loop in simple scenario

Juancarlos Laguardia brassman785 at gmail.com
Mon Mar 2 22:41:43 CET 2009


I have a problem in which i am having trouble vectorizing a snippet of 
my code to avoid a for loop.  A basic example of what I'm trying to do 
is below.

#simple example of problem

x = c(1,1,3,3,6,7,8,8,9)

# I create a vector that contains the unique values of x

y = unique(x)

  y = c(1,3,6,7,8,9)

####  Now I want to create a vector, say z, in which has the same length 
of y, but counts how many repetitions occurred for x.

## I want

z = c(2,2,1,1,2,1)

##   The only way I've been able to think about this problem is in terms 
of a for/while loop to generate z.  I'm having trouble thinking on this one.

If someone could help me out, I would greatly appreciate this.


More information about the R-help mailing list