SSG_08
SSG_08

Reputation: 47

Merging multiple data frames using only a loop in R

I have multiple data sets, which are returned by function return_page(page), where 'page' indicates the page number respectively. Each data set has the same number of rows and columns, and they also have same names for each page. I need to merge 5 pages to create a single data frame using only FOR loop. So far, I have done it using the following function:

data <- rbind(return_page(1),return_page(2),return_page(3),return_page(4),return_page(5))

Yet, it doesn't meet my needs, since it isn't a loop and uses hard-coding. Please, let me know how can I accomplish this task using a loop.

Upvotes: 1

Views: 2361

Answers (2)

GuedesBF
GuedesBF

Reputation: 9858

You could use an apply or map function here:

library(purrr)

map(1:5, return_page)%>%rbind.data.frame(.)

For a solution limited to a for loop, see the answer by @Soldalma below

Upvotes: 0

Soldalma
Soldalma

Reputation: 4758

Have you tried this?

df <- return_page(1)

for (i in 2:5) {
  df <- rbind(df, return_page(i))
}

Upvotes: 3

Related Questions