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.

2
  • Just make this temp_var a data.frame outside the loop: df <- data.frame(temp_var) Commented Jul 16, 2015 at 15:22
  • @AlexeyFerapontov - Thank you for the suggestion Commented Jul 17, 2015 at 14:49

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I am interested in knowing why for loops are not recommended in R?
@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: stackoverflow.com/questions/7142767/why-are-loops-slow-in-r.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.