Repeat data frames in R
· 阅读需 3 分钟
Briefly introduce how to create data frames with repeated suffixes in R
Sometimes, we want to create some data frames with a fixed prefix and a
range of numbers. For example, we want to create 10 data frames with
names df1, df2, …, df10.
We have two ways to do this.
- One list: create a list of data frames and store them into a list df_list.
- Individual dataframe: create 10 data frames with names
df1,df2, …,df10directly.
One list
Firstly, let’s try to create a list of data frames and store them into a
list df_list.
library(dplyr)
num <- 1:10
# Create an empty list
df_list <- list()
# Loop through the numbers
for (i in num) {
# suppose we have different values for x and y
temp <- data.frame(x = rnorm(10), y = rnorm(10)) %>%
# Add a column with the current number
mutate(id = i)
# Add the data frame to the list
df_list[[i]] <- temp
}
Then, we can use dplyr to transform the list to a dataframes by using
bind_rows.
df <- bind_rows(df_list)
head(df)
A data.frame: 6 x 3
| x <dbl> | y <dbl> | id <int> | |
|---|---|---|---|
| 1 | -0.4229988 | -0.2171858 | 1 |
| 2 | 1.5798157 | 0.9990500 | 1 |
| 3 | -0.1763058 | -1.1700267 | 1 |
| 4 | 0.5552782 | -0.4305593 | 1 |
| 5 | 0.2594807 | 1.3306744 | 1 |
| 6 | 0.5152127 | 0.4716893 | 1 |
Individual dataframe
Secondly, let’s try to create 10 data frames with names df1, df2, …,
df10 directly.
Then, we can use dplyr to transform the dataframes to a dataframes by
using bind_rows.
num <- 1:10
for (i in num) {
# use assign to create a new variable.names
assign(paste0("df_", i), data.frame(x = rnorm(10), y = rnorm(10)))
}
# List all the data frames
ls(pattern = "df_")
- ‘df_1’
- ‘df_10’
- ‘df_2’
- ‘df_3’
- ‘df_4’
- ‘df_5’
- ‘df_6’
- ‘df_7’
- ‘df_8’
- ‘df_9’
- ‘df_list’
If you want to create a list to store all these variables, we can use
get function to get the variable by its name.
# For example, we want to store in df_list2
df_list2 <- list()
for (i in num) {
# use assign to create a new variable.names
df_list2[[i]] <- get(paste0("df_", i))
}
