R按列和排列列,并将多个列置于同一类别下

R按列和排列列,并将多个列置于同一类别下,r,sorting,dataframe,linear-regression,binning,R,Sorting,Dataframe,Linear Regression,Binning,我有一个数据框,其中“收入”是数字,a,B,C,D,E。。。是二进制向量 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…1000

我有一个数据框,其中“收入”是数字,a,B,C,D,E。。。是二进制向量

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…1000列中,我想保留colSums最大的前400列。对于其他600列,我想将它们作为标记为“other”的一列进行分类,该列将具有0或1(基本上,“other”列中的每一行条目都是一个or,介于最少的colSum 600列之间)


总的来说,目的是最终使用A、B、C、D、E……中最“流行”的前400列。。。(其中流行度在二元向量中以“1”衡量)对收入进行线性回归。

假设
dfs
是数据框

# +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