data.table - 删除 R 中计数不相等的所有组
data.table - removing all groups with unequal count in R
我想按 ID 对 data.table 进行分组,并删除 count
not 多年来具有相同值的所有组。
如果 ID 和计数组合不唯一,可能会删除具有该 ID 的所有行?
我正在寻找适用于大型 data.table
的解决方案
数据:
# example data
ID <- c(rep("A", 5), rep("B", 6), rep("C", 2), rep("D", 3), rep("E", 4))
count <- c(rep(3, 5), rep(4, 6), rep(1, 2), c(1,3,3), rep(1, 4))
year <- as.numeric(c(rep(c(2012, 2013, 2014, 2015), 4), 2012, 2013, 2015, 2016))
mydata <- cbind(ID, year, count)
mydata <- as.data.table(mydata)
mydata <- setorder(unique(mydata))
不确定这是最优雅的解决方案,也许有人有更好的解决方案。与此同时:
mydata[, k := length(unique(count)), by=ID][k==1][,k:=NULL]
编辑:
复制自上面的link,正确的解决方案:
mydata[ , if(uniqueN(count) == 1) .SD, by = ID]
我实际上找到了问题的答案:
q <- which(duplicated(mydata[,c('ID','year')]))
if(length(k) > 0){
prob <- mydata[k, ID]
mydata <- mydata[!ID %in% prob]
}
我想按 ID 对 data.table 进行分组,并删除 count
not 多年来具有相同值的所有组。
如果 ID 和计数组合不唯一,可能会删除具有该 ID 的所有行?
我正在寻找适用于大型 data.table
的解决方案数据:
# example data
ID <- c(rep("A", 5), rep("B", 6), rep("C", 2), rep("D", 3), rep("E", 4))
count <- c(rep(3, 5), rep(4, 6), rep(1, 2), c(1,3,3), rep(1, 4))
year <- as.numeric(c(rep(c(2012, 2013, 2014, 2015), 4), 2012, 2013, 2015, 2016))
mydata <- cbind(ID, year, count)
mydata <- as.data.table(mydata)
mydata <- setorder(unique(mydata))
不确定这是最优雅的解决方案,也许有人有更好的解决方案。与此同时:
mydata[, k := length(unique(count)), by=ID][k==1][,k:=NULL]
编辑: 复制自上面的link,正确的解决方案:
mydata[ , if(uniqueN(count) == 1) .SD, by = ID]
我实际上找到了问题的答案:
q <- which(duplicated(mydata[,c('ID','year')]))
if(length(k) > 0){
prob <- mydata[k, ID]
mydata <- mydata[!ID %in% prob]
}