rsubsetdifference

Select groups with more than one distinct value


I have data with a grouping variable ("from") and values ("number"):

from number
   1      1
   1      1
   2      1
   2      2
   3      2
   3      2

I want to subset the data and select groups which have two or more unique values. In my data, only group 2 has more than one distinct 'number', so this is the desired result:

from number
   2      1
   2      2

Solution

  • Several possibilities, here's my favorite

    library(data.table)
    setDT(df)[, if(+var(number)) .SD, by = from]
    #    from number
    # 1:    2      1
    # 2:    2      2
    

    Basically, per each group we are checking if there is any variance, if TRUE, then return the group values


    With base R, I would go with

    df[as.logical(with(df, ave(number, from, FUN = var))), ]
    #   from number
    # 3    2      1
    # 4    2      2
    

    Edit: for a non numerical data you could try the new uniqueN function for the devel version of data.table (or use length(unique(number)) > 1 instead

    setDT(df)[, if(uniqueN(number) > 1) .SD, by = from]