ML_Enthousiast
ML_Enthousiast

Reputation: 1269

How to rbind dataframes in a for loop

I am trying to create a dataframe combined of many dataframes created by a for loop. I know for loop is not recommended but since I feel more confortable using it. I am looping through a list of elements in keyword_page of a dataframe df.

What I did works fine but my method is create all the dataframes with the for loop and only combine them when the for loop is over.

I would like to have a method that will add the dataframe to the stack of the previous dataframes created in the for loop, so that I can delete the dataframe right away after the rbind within the for loop and not at the end of it.

i=1

for (page in as.character(df$website)){

  keywordA <- data.frame(matrix(page))
  keywordB <- data.frame(matrix("REVIEW"))
  keywordC <- data.frame(df$keyword_page[i])

  assign(paste0('table_page', i), data.frame(keywordA, keywordB, keywordC))

i <- i +1

}
table_page_all <- rbindlist(mget(ls(pattern = "^table_page\\d+")))
colnames(table_page_all) <- c("KEYWORD A", "KEYWORD B", "KEYWORD C")
rm(list = (ls(pattern = "^table_page\\d+")))

Thanks!

Upvotes: 1

Views: 420

Answers (1)

LocoGris
LocoGris

Reputation: 4480

Try this:

i=1
table_page_all  <- data.frame()
for (page in as.character(df$website)){

  keywordA <- data.frame(matrix(page))
  keywordB <- data.frame(matrix("REVIEW"))
  keywordC <- data.frame(df$keyword_page[i])


   i <- i +1
   table_page_all  <- rbind(table_page_all, data.frame(keywordA, keywordB, keywordC))
}

colnames(table_page_all) <- c("KEYWORD A", "KEYWORD B", "KEYWORD C")

Upvotes: 1

Related Questions