[R] Avoiding a loop

jim holtman jholtman at gmail.com
Mon Apr 21 18:53:55 CEST 2008


Will this do it for you:

# Seed and data frames X, Y and Z
set.seed(123)
X=matrix(rnorm(300),ncol=5)
Y=matrix(rpois(300,10),ncol=5)
Z=matrix(rexp(300,1),ncol=5)

index <- seq(1, by=3, length=nrow(X))
FINAL <- matrix(ncol=5, nrow=3*nrow(X))
FINAL[index,] <- X
FINAL[index + 1,] <- Y
FINAL[index + 2,] <- Z


On Mon, Apr 21, 2008 at 11:44 AM, Jorge Ivan Velez
<jorgeivanvelez at gmail.com> wrote:
> Dear R-users,
>
> I've been working with three different data sets (X, Y and Z) with the same
> dimension (i.e, n \times k). What I needed to do was to conform a 4th data
> set, i.e. FINAL, which first row was the X's first row, its second row was
> the Y's first row, and its third row was the Z's first row, and so on.
>
> My code is below. Is it possible to avoid the loop?
>
> Thanks in advance,
>
> Jorge
>
>
>
> # ----- Code starts here
>
> # Seed and data frames X, Y and Z
> set.seed(123)
> X=matrix(rnorm(300),ncol=5)
> Y=matrix(rpois(300,10),ncol=5)
> Z=matrix(rexp(300,1),ncol=5)
>
> # First five columns and rows
> X[1:3,1:5]
> Y[1:3,1:5]
> Z[1:3,1:5]
>
> # FINAL' six rows
> res=NULL; for(i in 1:nrow(X)) res=rbind(res,X[i,],Y[i,],Z[i,])
> FINAL=data.frame(from.data=c('X','Y','Z'),res)
> FINAL[1:9,1:6]
>
> # ----- Code ends here
>
>        [[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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list