snair.stack
snair.stack

Reputation: 415

Subset the remaining of a dataframe using another subset

I have a sample dataset. I've created a subset of the original data frame using some condition. Now I need to extract the remaining contents of the original sample data frame, except the subset created. How can I do this?

data("mtcars")
fulldf <- mtcars
subdf <- subset.data.frame(fulldf, subset = fulldf$disp < 100)
restdf <- subset.data.frame(fulldf, subset = <fulldf without subdf>)

There are a lot of questions on subsetting data frames in R, but I couldn't find one that satisfied my requirement. Also the final solution need not necessarily be using subset.data.frame. Any method/package will do.

Upvotes: 1

Views: 673

Answers (1)

akrun
akrun

Reputation: 887048

It is better to assign the logical condition in base R to an object identifier and then negate (!)

i1 <- fulldf$disp < 100
subdf <- subset.data.frame(fulldf, subset = i1)
restdf <- subset.data.frame(fulldf, subset = !i1) 

Also another option is to create a list of two datasets with split

lst1 <- split(fulldf, i1)

If the 'subdf' is creating with multiple conditions (not clear though), one option is to add a sequence variable in the data and then subset with %in%

fulldf$ind <- seq_len(nrow(fulldf))

then after the 'subdf' step

restdf <- subset(fulldf, !ind %in% subdf$ind)

and remove the 'ind' columns

restdf$ind <- NULL
subdf$ind <- NULL

Upvotes: 1

Related Questions