Select groups with more than one distinct value

人盡茶涼 提交于 2019-11-26 02:25:26

问题


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 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]



回答2:


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



回答3:


Using concept of variance shared by David but doing it dplyr way:

library(dplyr) 
df %>% 
   group_by(from) %>% 
   mutate(variance=var(number)) %>% 
   filter(variance!=0) %>% 
   select(from,number)

    #Source: local data frame [2 x 2]
    #Groups: from

       #from number
   #1    2      1
   #2    2      2


来源:https://stackoverflow.com/questions/31649049/select-groups-with-more-than-one-distinct-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!