[R] Interlacing two vectors
kjetil brinchmann halvorsen
kjetil at entelnet.bo
Thu Aug 21 04:37:06 CEST 2003
On 21 Aug 2003 at 9:16, Murray Jorgensen wrote:
Hola!
I'm not sure if this is better, but if we can interlace first
1:n with (n+1):2n the rest is indexing:
> x <- 1:10
> y <- 1:10 + 0.5
> interl <- function(n) {
+ res <- numeric(2*n)
+ for (j in 1:n) {
+ res[2*j-1] <- j
+ res[2*j] <- n+j }
res
+ }
> interl(4)
[1] 1 5 2 6 3 7 4 8
> c(x,y)[interl(10)]
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0
7.5 8.0
[16] 8.5 9.0 9.5 10.0 10.5
You can do some testing to se what is fastest.
Kjetil Halvorsen
> I want to interlace two vectors. This I can do:
>
> > x <- 1:4
> > z <- x+0.5
> > as.vector(t(cbind(x,z)))
> [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5
>
> but this seems rather inelegant. Any suggestions?
>
> Murray
>
> --
> Dr Murray Jorgensen http://www.stats.waikato.ac.nz/Staff/maj.html
> Department of Statistics, University of Waikato, Hamilton, New Zealand
> Email: maj at waikato.ac.nz Fax 7 838 4155
> Phone +64 7 838 4773 wk +64 7 849 6486 home Mobile 021 1395 862
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
More information about the R-help
mailing list