Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining data frames with missing data frames with rbind

Tags:

dataframe

r

rbind

I am using the following command for combining data from different dataframes.Some of the data frames are missing like data 4 etc.,

filings<- rbind.pages(list(data1,data2,data3,data4,data5))
Error in stopifnot(is.list(pages)) : object 'data4' not found

I am getting the above error. I have about 1000 data frames and there are some missing dataframes which are not known. Is there way I can tackle this issue to skip missing data frames?

Thanks!

like image 596
user3570187 Avatar asked Aug 31 '26 17:08

user3570187


1 Answers

This should work:

possibleDfs <- paste0('data', 1:1000)
existingDfIndices <- sapply(possibleDfs, exists)
existingDfs <- mget(possibleDfs[existingDfIndices])

do.call(rbind, existingDfs)

First, we created a vector of the names of the data.frames:

head(possibleDfs)
[1] "data1" "data2" "data3" "data4" "data5" "data6"

Then, we used sapply(possibleDfs, exists) to get a logical vector indicating which data.frames exist.

We then subseted possibleDfs with existingDfIndices to get the names of the data.frames that exist, to which we apply mget to obtain a list of those data.frames.

Lastly, we use do.call and rbind to bind all of the data.frames.

like image 114
Richard Border Avatar answered Sep 03 '26 09:09

Richard Border