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 回答1: 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