Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cbind the column generated in a loop in R

Tags:

for-loop

r

cbind

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, ...

like image 572
cppython Avatar asked Dec 08 '22 02:12

cppython


2 Answers

There are many ways to achieve what you have described. Here is one approach that will work in many circumstances.

# start with an empty list
mydata <- list()

# run through your loop, adding each vector to the list
for(i in 1:10){
    # whatever is in your loop
    mydata[[i]] <- # result of this iteration of loop
}

# turn your list into a dataframe
mydf <- data.frame(mydata)

# write dataframe to a file
write.csv(mydf, file="destfile.csv")
like image 70
tegancp Avatar answered Dec 10 '22 16:12

tegancp


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
like image 32
josliber Avatar answered Dec 10 '22 16:12

josliber