Home > Software design >  R- Appending new data frames in a for loop
R- Appending new data frames in a for loop

Time:08-13

I'm trying to append dataframes of tweets which i generate in a for loop to one another at the end of each iteration of a for-loop:

replys <- data.frame()
for (i in 1:nrow(i_tweets)) {                
  iteration_i <- get_all_tweets(
    conversation_id= i_tweets$conversation_id[i],  
    start_tweets = "2017-05-16T00:00:00Z",        
    end_tweets = "2022-08-06T00:00:00Z",
    n= 1,
    bearer_token = get_bearer(),
    data_path = "replys/")
  rbind(replys, iteration_i)}

I know that the get_all_tweets function works fine and that the loop is successfully iterating over the rows of my input data. But at the end I always end up with the iteration_i-dataframe containing the tweets for the last iteration but the replys-dataframe remains empty. Can you tell me whats my error and how I can fix it, so that the loop iterates over all my rows and finally binds all new dataframes together?

CodePudding user response:

You are not updating your data frame replys while rbinding it with iteration_i data. Please try below code:

replys <- data.frame()
for (i in 1:nrow(i_tweets)) {                
  iteration_i <- get_all_tweets(
    conversation_id= i_tweets$conversation_id[i],  
    start_tweets = "2017-05-16T00:00:00Z",        
    end_tweets = "2022-08-06T00:00:00Z",
    n= 1,
    bearer_token = get_bearer(),
    data_path = "replys/")
  replys<-rbind(replys, iteration_i)}
  • Related