2014-01-10 36 views
0

我想獲取最大值並將該colnames分配回數據框。我試圖循環它。有什麼建議麼?謝謝which.max併爲R中的數據框指定colnames值

new<-data.frame(id=seq(1:5),att1=rnorm(5,1),att2=rnorm(5,1),att3=rnorm(5,1)) 
for (i in 1:nrow(new)) 
new$type<-names(which.max(new[i,2:4])) 

id  att1  att2  att3 type 
1 -1.1735401 0.1269600 0.6178781 att3 
2 1.9650696 -0.2129732 0.5030030 att3 
3 -0.0901813 4.3937726 1.1886939 att3 
4 0.1719326 1.9478824 2.2497336 att3 
5 2.1359702 2.3347643 2.6607773 att3 
+0

我認爲你應該使用'.. new $ type [i] < - ..'。 –

回答

3

嘗試apply;

new$type <- names(new)[apply(new[-1], 1, which.max) + 1] 

    id  att1  att2  att3 type 
1 1 1.77432474 0.3306480 0.9693518 att1 
2 2 -0.00585121 0.2115700 0.6579220 att3 
3 3 0.23611749 0.7180739 1.9325201 att3 
4 4 0.43156117 0.9980831 -1.2525760 att2 
5 5 2.10921757 1.3001635 0.4259629 att1 
+0

如果有兩列具有相同的值,它只會得到一個結果。 –

+0

'new $ type <-apply(new [,2:5],1,function(x)names(which(x == max(x))))''在'apply'後​​嘗試找到解決方案。 tahnks –

2
names(new)[2:4][max.col(new[, 2:4])] 

作爲一般規則,不與數據幀使用apply。它會將輸入df轉換爲矩陣,如果您有任何字符或因子列,則會生成字符矩陣。

+0

是的,'apply'將把數據幀轉換成矩陣。但同樣適用於'max.col'。看看代碼,特別是下面這行代碼:'m < - as.matrix(m)'。 –

+0

@SvenHohenstein我確實說過「作爲一般規則」。在這種情況下,所有必需的列都是數字,所以使用'apply'(在做適當的子集之後)是安全的。但是,通常你想對包含數字和字符/因子列的數據框進行按行操作,而'apply'則不會有幫助。 –

+0

我完全同意。 –

相關問題