I am trying to rbind a series of dataframes in r. Each dataframe has the same basic structure. Here is what one dataframe might look like.
data1 <- data.frame (id = c (1000, 1001, 1002, 1003),
time = c(1, 1, 1, 1),
start = c(1/1/2020, 1/1/2020, 1/1/2020, 1/1/2020),
end = c (1/2/2020, 1/3/2020, 1/4/2020, 1/2/2020) )
I created some code to generate a listing of all the dataframes. In my project, the number of dataframes is going to change depending upon the specific task. The user will input how many frames they are expecting to have. The dataframe list will generate a listing of all dataframes.
# listing of dataframes
# in this example, lets say we have 100 dataframes
numberofdataframes <- 1:100
# create a listing of all new frames
dataframelist <- paste0 ("data", numberofdataframes, sep = "", collapse = NULL)
dataframelist
My plan is to rbind this list of dataframes I created.
rbind (dataframelist )
Here is what I expect my output to be.
id time start end
1000 1 1/1/2020 1/2/2020
1000 1 1/1/2020 1/3/2020
1000 1 1/1/2020 1/4/2020
1000 1 1/1/2020 1/2/2020
1000 2 2/1/2020 2/2/2020
1000 2 2/1/2020 2/2/2020
1000 2 2/1/2020 2/2/2020
1000 2 2/1/2020 2/2/2020
1000 3 3/1/2020 3/2/2020
1000 3 3/1/2020 3/2/2020
1000 3 3/1/2020 3/2/2020
1000 3 3/1/2020 3/2/2020
etc.
However, when I run the code, I just get an rbind of dataframelist.
"data1"
"data2"
"data3"
etc.
I have checked online and there are a few different solutions I have tried. One method is to use do.call (Recombining a list of Data.frames into a single data frame). This method gives me the exact same error. and tried to use do.call and I get the same error.
Other solutions recommend rbindlist. When I use rbind list, I get a slightly different error.
> rbindlist (dataframelist )
Error in rbindlist(dataframelist ) :
Item 1 of input is not a data.frame, data.table or list
I think r is not interpreting the items in dataframelist as dataframes but as characters. When using rbindlist or do.call, what should the listing of dataframes look like. I think this is where the problem may be occuring?
CodePudding user response:
The dataframelist
constructed is a vector
of object names. We need to get the value of the objects and it can be done with mget
- returns it in a list
(assuming these are objects created in the global env)
library(data.table)
rbindlist(mget(dataframelist))
CodePudding user response:
Tidyverse solution:
# Load packages
library(tidyverse)
# Create single dataframe from existing objects in dataframelist
map(dataframelist, ~if(exists(.)){get(.)}) %>% bind_rows()