2014-01-10 32 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

我完全同意。 –

相关问题