0

I am trying to look up the index or name of a data frame based on the maximum of the aggrate values of that data frame, for example:

df <- data.frame(
        id = 1:6, 
        v1 = c(3, 20, 34, 23, 23, 56),
        v2 = c(1, 3, 4, 10, 30, 40),
        v3 = c(20, 35, 60, 60, 70, 80))

  id v1 v2 v3  
1  1  3  1 20  
2  2 20  3 35  
3  3 34  4 60  
4  4 23 10 60  
5  5 23 30 70  
6  6 56 40 80  

> colSums(as.data.frame(df[[1]]))  
df[[1]]  
     21   

> colSums(as.data.frame(df[[2]]))  
df[[2]]   
    159   

> colSums(as.data.frame(df[[3]]))  
df[[3]]   
     88  

So for example the maximum result using colSums is 159, and I'm trying to figure out how to to return 'df[[2]]'

4

1 に答える 1

3

まず、あなたは単にcolSumsあなたのdata.frame

> colSums(df)
 id  v1  v2  v3 
 21 159  88 325 

サブセット化も簡単です

> df[which.max(colSums(df))]
  v3
1 20
2 35
3 60
4 60
5 70
6 80

または、最初の行に示されているように、インデックスが必要な場合は次のようになります。

> which.max(colSums(df))
v3 
 4 

また、同じ最大合計を持つ列が複数ある可能性があり、それらすべてを返したい場合は、最初の出現のみを返すのwhich(colSums(df) == max(colSums(df)))代わりにを使用できることにも注意してください。which.max

于 2012-04-28T16:58:57.503 に答える