# [R] Avoiding a loop

From: Jorge Ivan Velez <jorgeivanvelez_at_gmail.com>
Date: Mon, 21 Apr 2008 11:44:32 -0400

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?

Jorge

# ----- Code starts here

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. Received on Mon 21 Apr 2008 - 15:57:56 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 21 Apr 2008 - 18:30:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.