2016-11-20 27 views
-1

我有一個數據框,其中'Earning'是數字,A,B,C,D,E ...是二進制向量。R根據colSums和bin在同一類別下安排多個列

Earning A B C D E ...**1000 such binary vector columns** 
    21 1 0 0 1 1 
    45 0 0 0 1 1 
    67 0 0 0 1 1 
    23 0 0 0 0 1 
    44 0 0 0 1 1 
    77 1 1 0 0 1 
    89 0 1 0 1 1 
    90 1 0 0 0 0 

在A,B,C .... 1000columns中,我想保留其colSums最大的前400列。對於其他600列,我想將它們作爲一列標記爲「其他」,它將具有0或1(基本上,「其他」列中的每一行條目是最小colSum 600列之間的OR)。總體而言,意圖是最終使用A,B,C,D,E ...(其中流行度在二進制向量中被測量爲'1')的最受歡迎的前400列線性迴歸與收益。

回答

0

假設dfs是data.frame與您的數據。

# +1/-1 is to keep 'Earnings' at the beginning of the data.frame 
new_order = order(colSums(dfs[,-1], na.rm = TRUE), decreasing = TRUE) + 1 
res = cbind(
    dfs[, c(1, new_order[1:400])], 
    other = 1*(rowSums(dfs[, new_order[-(1:400)]])>0) 
    ) 

res產生的data.frame具有新的列順序。