how to cbind the column generated in a loop in R
Asked Answered
H

2

5

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

Hardheaded answered 19/6, 2015 at 21:8 Comment(0)
E
8

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")
Ejectment answered 19/6, 2015 at 21:28 Comment(2)
This is a nice and simple way. Thanks a lot. Just want to give a feedback to anyone who will implement this piece of code. mydata[[i]] should be mydata[i], and I run it and get what I want. Thanks to tegancp!Hardheaded
The code works for me too. I'm just having problems to convert the list to data frame. I got the message Error in data.frame(NULL, c(0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, : arguments imply differing number of rows: 0,.... . Any help?Anamariaanamnesis
D
7

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
Demoniac answered 19/6, 2015 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.