【问题标题】:Getting the name of the column with the minimum value for a row in a dataframe [duplicate]获取数据框中行的最小值的列名称[重复]
【发布时间】:2019-12-23 20:49:57
【问题描述】:

输入数据

soo<-structure(list(Mycol1 = c(11.9, 7.8, 8.2, 14.7, 1, 21.7, 0, 48.6, 
0, 2.8), Mycol2 = c(10.2, 2.7, 6.4, 55.1, 1, 8.6, 0, 0, 0, 1.9
)), row.names = c(NA, 10L), class = "data.frame")

瞄准

我想提取每行最大值的列名。

尝试

我可以得到最大值,但是如何得到它所在的列的名称。

do.call(pmin, c(soo, na.rm = TRUE))

【问题讨论】:

  • 您要逐行计算最大值还是最小值?您的标题和正文不匹配。你能改正吗?

标签: r


【解决方案1】:

你可以这样做:

soo$max_col = colnames(soo)[apply(soo, 1, which.max)]

输出:

   Mycol1 Mycol2 max_col
1    11.9   10.2  Mycol1
2     7.8    2.7  Mycol1
3     8.2    6.4  Mycol1
4    14.7   55.1  Mycol2
5     1.0    1.0  Mycol1
6    21.7    8.6  Mycol1
7     0.0    0.0  Mycol1
8    48.6    0.0  Mycol1
9     0.0    0.0  Mycol1
10    2.8    1.9  Mycol1

【讨论】:

  • 谢谢@AnkurSinha。在真实数据集中有 na。这有关系吗?
  • 刚看到你的评论。我的解决方案会处理它,但会发出警告。 Ronak 的答案很干净;)因此,我不会重新发布或编辑我的答案。
【解决方案2】:

我们可以使用max.col,它将在每行中返回带有max值的列号,并处理NAs,我们可以使用0来处理replace。我们使用ties.method = "first",所以如果我们有一个将最大值连成一行,我们总是选择第一个最大值。

soo$max_col <- names(soo)[max.col(replace(soo, is.na(soo),0),ties.method = "first")]

soo
#   Mycol1 Mycol2 max_col
#1    11.9   10.2  Mycol1
#2     7.8    2.7  Mycol1
#3     8.2    6.4  Mycol1
#4    14.7   55.1  Mycol2
#5     1.0    1.0  Mycol1
#6    21.7    8.6  Mycol1
#7     0.0    0.0  Mycol1
#8    48.6    0.0  Mycol1
#9     0.0    0.0  Mycol1
#10    2.8    1.9  Mycol1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2021-11-04
    • 1970-01-01
    • 2017-11-02
    • 2019-08-29
    • 2015-01-31
    • 2020-10-05
    相关资源
    最近更新 更多