【问题标题】:which.max and assign colnames value to dataframe in R [duplicate]which.max 并将 colnames 值分配给 R 中的数据框 [重复]
【发布时间】:2014-01-29 03:58:38
【问题描述】:

我想获取最大值并将列名分配回数据框。我试图循环它。有什么建议?谢谢

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] &lt;- ..

标签: r


【解决方案1】:
names(new)[2:4][max.col(new[, 2:4])]

一般来说,不要将apply 与数据框一起使用。它将输入 df 转换为矩阵,如果您有任何字符或因子列,它将生成字符矩阵。

【讨论】:

  • 是的,apply,会将数据框转换为矩阵。但同样适用于max.col。查看代码,尤其是以下行:m &lt;- as.matrix(m).
  • @SvenHohenstein 我确实说过“作为一般规则”。在这种情况下,所有必要的列都是数字的,因此使用 apply 是安全的(在您进行适当的子集设置之后)。但通常您想对涉及数字和字符/因子列的数据框进行逐行操作,而 apply 将无济于事。
  • hmmm.. 如果我想返回多个名称怎么办?如果有两列共享相同的最大值?
【解决方案2】:

试试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

【讨论】:

  • 如果有两列具有相同的值,它只会得到一个结果。
  • new$type&lt;-apply(new[,2:5],1,function(x) names(which(x==max(x)))) 在我尝试使用apply 后找到了解决方案。塔恩克斯
猜你喜欢
  • 2013-05-19
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2016-09-16
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多