[R] Help on vectorizing

From: remko duursma <remkoduursma_at_hotmail.com>
Date: Sun, 09 Mar 2008 23:55:32 +0000

 

Dear R-helpers,  

I have two problems that I don't know how to vectorize (but would like to because my current solution is slow).  

# 1.
#I have a vector x:
 

x <- c(3, 0, 1, 0, 2, 2, 2, 0, 4, 2)  

#I want this translated into a new vector based on x,so that each element of x
#is the number of zeroes, followed by a 1. The new vector would look like:
 

#> r# [1] 0 0 0 1 1 0 1 1 0 0 1 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1
 

# I only found a solution that loops, and it's a bit ugly:
r <- c()for(i in 1:length(x))r <- c(r, rep(0,pmax(0,x[i])),1)    

# 2.
# The other way around, so that we have the vector r, and want to find x.
# I have a (very) ugly solution:

chars <- paste(r,collapse="")zeros <- strsplit(chars,"1")x <- nchar(zeros[[1]])      

Thanks for your help!  

Remko Duursma

        [[alternative HTML version deleted]]



R-help_at_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. Received on Mon 10 Mar 2008 - 00:01:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 10 Mar 2008 - 01:30:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive