[英]subsetting based on number of observations in a factor variable
您如何根据对因子变量水平进行观察的次数来进行子集化? 我有一个包含1,000,000行和近3000个水平的数据集,我想用少得多的200个观察值来划分水平。
data <- read.csv("~/Dropbox/Shared/data.csv", sep=";")
summary(as.factor(data$factor)
10001 10002 10003 10004 10005 10006 10007 10009 10010 10011 10012 10013 10014 10016 10017 10018 10019 10020
414 741 2202 205 159 591 194 678 581 774 778 738 1133 997 381 157 522 6
10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038
398 416 1236 797 943 386 446 542 508 309 452 482 425 272 261 291 145 598
10039 10040 10041 10043 10044 10065 10069 10075 10080 10104 10105 10106 10110 10112 10115 10117 10119 10121
119 263 9 9 179 390 70 465 19 3 7 5 4 1 1 1 2 6
10123 10128 10150 10152 10154 10155 10168 10170 10173 10174 10176 10199 10210 10220 10240 10265 10270 10271
2 611 8 1 1 2 10 1 6 5 5 2 5 2 1 3 5 2
从上面的摘要中可以看出,有些因素只有几分,我想删除小于100的因素。
我尝试了以下操作,但没有成功:
for (n in unique((data$factor))) {
m<-subset(data, factor==n)
o<-length(m[,1])
data<-ifelse( o<100, subset(data, factor!=n), data)
}
table
,并根据该子集的名称进行匹配。 此后可能会希望droplevels
。
信息技术部
一些样本数据:
set.seed(1234)
data <- data.frame(factor = factor(sample(10000:12999, 1000000,
TRUE, prob=rexp(3000))))
有一些类别,少数情况
> min(table(data$factor))
[1] 1
从少于100个具有相同factor
值的案例中删除记录。
tbl <- table(data$factor)
data <- droplevels(data[data$factor %in% names(tbl)[tbl >= 100],,drop=FALSE])
校验:
> min(table(data$factor))
[1] 100
请注意, data
和factor
不是很好的名称,因为它们也是内置函数。
我使用以下方法弄清楚了这一点,因为没有理由重复两次:
function (df, column, threshold) {
size <- nrow(df)
if (threshold < 1) threshold <- threshold * size
tab <- table(df[[column]])
keep <- names(tab)[tab > threshold]
drop <- names(tab)[tab <= threshold]
cat("Keep(",column,")",length(keep),"\n"); print(tab[keep])
cat("Drop(",column,")",length(drop),"\n"); print(tab[drop])
str(df)
df <- df[df[[column]] %in% keep, ]
str(df)
size1 <- nrow(df)
cat("Rows:",size,"-->",size1,"(dropped",100*(size-size1)/size,"%)\n")
df[[column]] <- factor(df[[column]], levels=keep)
df
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.