1

Starting with an empty dataframe, I need to fill the dataframe as follows: A for loop generates a fixed number of values in each iteration, and I need to add a new column with the values in that list, and giving the column a unique name, col_i (where i is the ith iteration of the loop).

How can this (seemingly simple task) be done?

citruspi
  • 6,709
  • 4
  • 27
  • 43
user1030497
  • 183
  • 1
  • 1
  • 14
  • 3
    As noted below, `cbind` is a good starting point. Also, please be aware that in general, starting with an empty data structure and adding things to it is literally one of the worst possible ways to do things in R. A good reference is Circle 2 of the [R Inferno](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf). – joran Jun 21 '12 at 00:39
  • @user1030497 Welcome to SO! If either of the answers below solved your problem, please make one as accepted by clicking the check mark next to the answer. – Ari B. Friedman Oct 09 '12 at 09:49

2 Answers2

5

The most efficient way to build a dataframe piecewise is to store your parts in a pre-allocated list, then put them together afterwards.

For example:

num.iters <- 10
l <- vector('list', num.iters) 
for (i in 1:num.iters) {
     l[[i]] <- rnorm(3)                       # the column data
     names(l)[i] <- paste('Col', i, sep='.')  # the column name 
} 
do.call(cbind, l)  # ... if your cols are the same datatype and you want a matrix
data.frame(l)      # otherwise
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
4

What's wrong with ?cbind?

The functions cbind and rbind are S3 generic, with methods for data frames. 
The data frame method will be used if at least one argument is a data frame 
and the rest are vectors or matrices. 

?colnames can also be applied to data.frames

ChrisW
  • 4,970
  • 7
  • 55
  • 92