Help on vectorizing
Try this: r <- unlist(sapply(x, function(x) c(rep(0, x), 1))) x2 <- diff(c(0, which(r==1))) - 1 identical(x, x2)
On Sun, Mar 9, 2008 at 7:55 PM, remko duursma <remkoduursma at hotmail.com> wrote:
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.