4

列 1 から 10 の各行の最大値と列の名前のみを含めるために、データフレーム (df) をサブセット化したいと考えています。

例のデータフレーム:

    0       1       2       3       4
    0.01    0.12    0.41    0.11    0.11
    0.13    0.12    0.33    0.14    0.07
    0.02    0.20    0.11    0.27    0.17
    0.11    0.33    0.04    0.09    0.24
    0.08    0.07    0.04    0.05    0.58

現在、私はこれを使用しています:

new_df[] <- apply(df[, 1:4], 1, max) #get the max value of current row
new_df<- subset(new_df, select = c(1)) #keep only one column

私はこれを得る:

0.41    
0.33
0.27
0.33
0.58

しかし、最大値の由来となった列名を取得できません。

望ましい結果:

    2   0.41    
    2   0.33
    3   0.27
    1   0.33
    4   0.58

よろしくお願いします。

4

1 に答える 1

3

これを試して

> t(apply(df, 1, function(x) c(which.max(x)-1, max(x))))
     [,1] [,2]
[1,]    2 0.41
[2,]    2 0.33
[3,]    3 0.27
[4,]    1 0.33
[5,]    4 0.58

別の方法:

> t(apply(df, 1, function(x) as.numeric(c(names(which.max(x)), max(x)))))
     [,1] [,2]
[1,]    2 0.41
[2,]    2 0.33
[3,]    3 0.27
[4,]    1 0.33
[5,]    4 0.58

DWin で提案されているように、別の代替手段は次のとおりです。

t(apply(df, 1, function(x) as.numeric(c(names(x)[which.max(x)], max(x)))))
于 2013-09-25T16:32:06.697 に答える