user3570187
user3570187

Reputation: 1773

Combining data frames with missing data frames with 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!

Upvotes: 3

Views: 1010

Answers (1)

nothing
nothing

Reputation: 3290

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.

Upvotes: 3

Related Questions