How to stack multiple data frames in R?

Asked

Viewed 702 times

3

I have 5 data frames in R with the same columns. I need to group them into a single data.frame, which command should I use?

Filenames are: parse10, parse20, parse30, parse40, parse50.

  • Reduce(rbind, list(df1, df2, df3)).

  • Do the dataframe names have anything in common? If yes, you can edit the question with an example?

1 answer

1

I’m going to assume that the dataframes have names with something in common, in this case:

  1. Begin with "analise";
  2. End in numbers.

So a combination of ls/mget can automate the creation of a list to be passed to Reduce.

df_names <- ls(pattern = "^analise\\d+$")
df_list <- mget(df_names)
Reduce(rbind, df_list)
             X          Y A
#1  -1.20706575  0.5060559 a
#2   0.27742924 -0.5747400 b
#3   1.08444118 -0.5466319 c
#4  -2.34569770 -0.5644520 d
#5   0.42912469 -0.8900378 e
#6  -0.47719270 -0.1102855 k
#7  -0.99838644 -0.5110095 l
#8  -0.77625389 -0.9111954 m
#9   0.06445882 -0.8371717 n
#10  0.95949406  2.4158352 o
#11  0.13408822 -1.4482049 u
#12 -0.49068590  0.5747557 v
#13 -0.44054787 -1.0236557 w
#14  0.45958944 -0.0151383 x
#15 -0.69372025 -0.9359486 y

Code to create data.

set.seed(1234)
analise10 <- data.frame(X = rnorm(5), Y = rnorm(5), A = sample(letters, 5, TRUE))
analise20 <- data.frame(X = rnorm(5), Y = rnorm(5), A = sample(letters, 5, TRUE))
analise30 <- data.frame(X = rnorm(5), Y = rnorm(5), A = sample(letters, 5, TRUE))
analise40 <- data.frame(X = rnorm(5), Y = rnorm(5), A = sample(letters, 5, TRUE))
analise50 <- data.frame(X = rnorm(5), Y = rnorm(5), A = sample(letters, 5, TRUE))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.