Juancarlos Laguardia
2009-Mar-02 21:41 UTC
[R] trying to get rid of for loop in simple scenario
Hi, 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. Carlos
Jorge Ivan Velez
2009-Mar-02 22:37 UTC
[R] trying to get rid of for loop in simple scenario
Dear Juan Carlos,> x = c(1,1,3,3,6,7,8,8,9) > table(x)x 1 3 6 7 8 9 2 2 1 1 2 1> z<-table(x) > zx 1 3 6 7 8 9 2 2 1 1 2 1> as.vector(z)[1] 2 2 1 1 2 1 Take a look at ?table and ?vector for more information. HTH, Jorge On Mon, Mar 2, 2009 at 4:41 PM, Juancarlos Laguardia <brassman785@gmail.com>wrote:> Hi, > > 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. > > Carlos > > ______________________________________________ > 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]]
Apparently Analagous Threads
- Is there a way to not use an explicit loop?
- code optimization problem ... using or not using "which" function
- should sub(perl=TRUE) also handle \E in replacement, to complement \U and \L?
- Cisco 7970
- Is it possible to have a remote Phone work behind Nat without a VPN?