Try this: > x <- 1:10 > pos <- c(1,4,7) > pat <- rep(seq_along(pos), times=diff(c(pos, length(x) + 1))) > split(x, pat) $`1` [1] 1 2 3 $`2` [1] 4 5 6 $`3` [1] 7 8 9 10
On Tue, May 4, 2010 at 11:29 AM, Joris Meys <jorism...@gmail.com> wrote: > Dear all, > > I'm trying to optimize code and want to avoid for-loops as much as > possible. > I'm applying a calculation on subvectors from a big one, and I get the > subvectors by using a vector of starting positions: > > x <- 1:10 > pos <- c(1,4,7) > n <- length(x) > > I try to do something like this : > pos2 <- c(pos, n+1) > > out <- c() > for(i in 1:n){ > tmp <- x[pos2[i]:pos2[i+1]] > out <- c(out, length(tmp)) > } > > Never mind the length function, I apply a far more complicated one. It's > about the use of the indices in the for-loop. I didn't see any way of doing > that with an apply, unless there is a very convenient way of splitting my > vector in a list of the subvectors or so. > > Anybody an idea? > Cheers > -- > Joris Meys > Statistical Consultant > > Ghent University > Faculty of Bioscience Engineering > Department of Applied mathematics, biometrics and process control > > Coupure Links 653 > B-9000 Gent > > tel : +32 9 264 59 87 > joris.m...@ugent.be > ------------------------------- > Disclaimer : http://helpdesk.ugent.be/e-maildisclaimer.php > > [[alternative HTML version deleted]] > > ______________________________________________ > 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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > -- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve? [[alternative HTML version deleted]] ______________________________________________ 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.