简体   繁体   中英

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!

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM