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, ...
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With