how to cbind the column generated in a loop in R

cppython picture cppython · Jun 19, 2015 · Viewed 12.6k times · Source

I have a for loop that gives me a column of data per run. I run the for loop in the range 0:4, so it gives me 5 columns. If I print it out, it is like column1, column2, ... I want to save all of the 5 columns together as a csv file. In this one single file, I want to have the 5 columns ordered by the order of the for loop, namely, column1, column2, ...

Answer

josliber picture josliber · Jun 19, 2015

Let's say you had a for loop like this:

for (i in 0:4) {
  this.column <- rep(i, 5)
}

To build a matrix out of the columns generated, you could change this to:

sapply(0:4, function(i) rep(i, 5))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    3    4
# [2,]    0    1    2    3    4
# [3,]    0    1    2    3    4
# [4,]    0    1    2    3    4
# [5,]    0    1    2    3    4

Basically you just create a function out of the interior of the for loop that takes the loop variable (i in this case) as input and returns the column. Then you call sapply with the loop indices and the first argument and the function as the second argument.

A fully vectorized approach could combine matrix and rep:

matrix(rep(0:4, each=5), nrow=5)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    3    4
# [2,]    0    1    2    3    4
# [3,]    0    1    2    3    4
# [4,]    0    1    2    3    4
# [5,]    0    1    2    3    4