Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 788
DK2 Avatar asked Jul 27 '15 09:07

DK2


2 Answers

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]
like image 142
David Arenburg Avatar answered Nov 10 '22 02:11

David Arenburg


You could try

 library(dplyr)
 df1 %>% 
     group_by(from) %>%
     filter(n_distinct(number)>1)
 #    from number
 #1    2      1
 #2    2      2

Or using base R

 indx <- rowSums(!!table(df1))>1
 subset(df1, from %in% names(indx)[indx])
 #   from number
 #3    2      1
 #4    2      2

Or

  df1[with(df1, !ave(number, from, FUN=anyDuplicated)),]
  #   from number
  #3    2      1
  #4    2      2
like image 6
akrun Avatar answered Nov 10 '22 04:11

akrun