如何删除具有一定数量观察值的所有唯一值?

How do I remove all unique values with certain amount of observations?

示例数据

date1 = seq(as.Date("2019/01/01"), by = "month", length.out = 29)
date2= seq(as.Date("2019/01/01"), by = "month", length.out = 29)
date3 = seq(as.Date("2019/01/01"), by = "month", length.out = 29)
date4 = seq(as.Date("2019/01/01"), by = "month", length.out = 10)

subproducts1=rep("1",29)
subproducts2=rep("2",29)
subproductsx=rep("x",29)
subproductsy=rep("y",10)

b1 <- c(rnorm(29,5))
b2 <- c(rnorm(29,5))
b3 <-c(rnorm(29,5))
b4 <- c(rnorm(10,5))


dfone <- data.frame("date"= c(date1,date2,date3,date4),
                "subproduct"= 
                  c(subproducts1,subproducts2,subproductsx,subproductsy),
                "actuals"= c(b1,b2,b3,b4))

问题:如何删除观察值小于或等于 10 的所有子产品?

我们可以通过 'subproduct' 和 filter 观察数 (n()) 大于或等于 10

的那些组进行分组
library(dplyr)
dfone %>%
     group_by(subproduct) %>%
     filter(n() >= 10) %>%
     ungroup

或者没有任何包依赖性

subset(dfone, subproduct %in% names(which(table(subproduct) >= 10)))

使用 plyr 库的 count() 函数,我们可以做到这一点。

dfcheck <- plyr::count(dfone$subproduct)
dfcheck <- dfcheck[dfcheck$freq>10,]
dftwo <- dfone[dfone$subproduct %in% dfcheck$x,]

count() 将为我们提供一个数据集,其中我们的变量出现在 x 列下,它们的频率出现在 freq 下。使用它,我们可以对超过 10 的值进行子集化,并对出现在我们的 >10 dfcheck 数据集中的子产品对我们的原始数据集进行子集化。