0

I want to create a new dataframe and keep adding variables in R with in a for loop. Here is a pseudo code on what I want:

X <- 100  
For(i in 1:X)  
{  
  #do some processing and store it a variable named "temp_var"

  temp_var[,i] <- z 
  #make it as a dataframe and keep adding the new variables until the loop completes  
}

After completion of the above loop the vector "temp_var" by itself should be a dataframe containing 100 variables.

Frank
  • 66,179
  • 8
  • 96
  • 180
Arun
  • 139
  • 1
  • 3
  • 9

1 Answers1

2

I would avoid using for loops as much as possible in R. If you know your columns before hand, lapply is something you want to use.

However, if this is constraint by your program, you can do something like this:

X <- 100
tmp_list <- list()
for (i in 1:X) {
    tmp_list[[i]] <- your_input_column
}
data <- data.frame(tmp_list)
names(data) <- paste0("col", 1:X)
Boxuan
  • 4,937
  • 6
  • 37
  • 73
  • Thanks for the answer. I am interested in knowing why for loops are not recommended in R? – Arun Jul 17 '15 at 14:51
  • @Arun There was a saying: if you have `for` loops in `R`, something must went wrong. That is obviously exaggerating, but it also conveys an idea that `for` loops should be generally avoided unless you know what you are doing. The main reason being, `for` loops will make your code run much slower. Instead, the `apply` family should be used. There is a more detailed discussion here: http://stackoverflow.com/questions/7142767/why-are-loops-slow-in-r. – Boxuan Jul 17 '15 at 20:52