[R] ? extended rep()
jim holtman
jholtman at gmail.com
Mon Oct 20 23:04:38 CEST 2008
will this do what you want:
> f.rep <- function(x, times){
+ # make sure the 'x' is long enough
+ x <- head(rep(x, length(times)), length(times))
+ rep(x, times)
+ }
>
> f.rep(c(0,1), c(3,4,5,6,7))
[1] 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0
>
On Mon, Oct 20, 2008 at 4:57 PM, Ted Harding
<Ted.Harding at manchester.ac.uk> wrote:
> Hi Folks,
> I'm wondering if there's a compact way to achieve the
> following. The "dream" is that, by analogy with
>
> rep(c(0,1),times=c(3,4))
> # [1] 0 0 0 1 1 1 1
>
> one could write
>
> rep(c(0,1),times=c(3,4,5,6))
>
> which would produce
>
> # [1] 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1
>
> in effect "recycling" x through 'times'.
>
> The objective is to produce a vector of alternating runs of
> 0s and 1s, with the lengths of the runs supplied as a vector.
> Indeed, more generally, something like
>
> rep(c(0,1,2), times=c(1,2,3,2,3,4))
> # [1] 0 1 1 2 2 2 0 0 1 1 1 2 2 2 2
>
> Suggestions appreciated! With thanks,
> Ted.
>
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 20-Oct-08 Time: 21:57:15
> ------------------------------ XFMail ------------------------------
>
> ______________________________________________
> 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list