Find complement of a data frame (anti - join)

前端 未结 7 1047
情深已故
情深已故 2020-11-21 11:20

I have two data frames(df and df1). df1 is subset of df. I want to get a data frame which is complement of df1 in df, i.e. return rows of the first data set which are not ma

相关标签:
7条回答
  • 2020-11-21 12:18

    You could also do some type of anti join with data.tables binary join

    library(data.table)
    setkey(setDT(df), heads)[!df1]
    #    heads
    # 1:  row1
    # 2:  row2
    # 3:  row4
    

    EDIT: Starting data.table v1.9.6+ we can join data.tables without setting keys while using on

    setDT(df)[!df1, on = "heads"]
    

    EDIT2: Starting data.table v1.9.8+ fsetdiff was introduced which is basically a variation of the solution above, just over all the column names of the x data.table, e.g. x[!y, on = names(x)]. If all set to FALSE (the default behavior), then only unique rows in x will be returned. For the case of only one column in each data.table the following will be equivalent to the previous solutions

    fsetdiff(df, df1, all = TRUE)
    
    0 讨论(0)
提交回复
热议问题