我想获取最大值并将该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
我认为你应该使用'.. new $ type [i] < - ..'。 –