2012-05-11 48 views
0

基於因子變量水平的觀測數目,您如何子集?我有一個包含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 
1
    2 611  8  1  1  2 10  1  6  5  5  2  5  2  1  3  5  2 

,你從彙總看,上面也有隻有少數OBS因素,我想刪除具有小於100

我嘗試以下的因素,但它沒't work:

for (n in unique((data$factor))) { 
    m<-subset(data, factor==n) 
    o<-length(m[,1]) 
    data<-ifelse(o<100, subset(data, factor!=n), data) 
} 

回答

6

table,子集,並基於該子集的名稱進行匹配。此後可能會想要droplevels


EIDT

一些樣本數據:

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 

注意datafactor不是很好的名字,因爲他們也內置函數。

+0

沒關係,我理解了它。 – cconnell

1

我想通了使用以下,因爲沒有理由做的事情兩次:

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 
} 
相關問題