在一行中找到最大值并返回列名

时间:2018-10-06 16:38:44

标签: r

这是我的数据框。我想在第3行中获得最高的数字并返回列名,即结果应为“ Height”

tt<-"Rows    Weight      Age        Height
    Cats -0.7289964  0.2194702 -2.4674780 
    Dogs  1.0889353  0.3167629 -0.9208548 
    Rats -0.6374692 -1.7249049  0.6567313 
    Mice -0.1348642  0.4507473 -1.7309010"

data <- read.table(text=tt, header=T)

2 个答案:

答案 0 :(得分:2)

正如@ G5W所指出的,第三行的年龄不是最高值,而是最高绝对值:

colnames(df)[max.col(abs(df[3, ]), ties.method = "first")]

如果您真的对最高价值感兴趣,那么:

colnames(df)[max.col(df[3, ], ties.method = "first")]

或者,如果您更喜欢tidyverse解决方案,则返回绝对值最高的列:

df %>%
  rowid_to_column() %>%
  filter(rowid == 3) %>%
  gather(col, val, Weight:Height) %>%
  filter(abs(val) == max(abs(val))) %>%
  select(-rowid, -val)

返回最大值的列:

df %>%
  rowid_to_column() %>%
  filter(rowid == 3) %>%
  gather(col, val, Weight:Height) %>%
  filter(val == max(val)) %>%
  select(-rowid, -val)

数据:

df <- read.table(text = "       Weight      Age        Height
Cats -0.7289964  0.2194702 -2.4674780 
                 Dogs  1.0889353  0.3167629 -0.9208548 
                 Rats -0.6374692 -1.7249049  0.6567313 
                 Mice -0.1348642  0.4507473 -1.7309010", header = TRUE)

答案 1 :(得分:0)

colnames(df)[max.col(df [3,],ties.method =“ first”)]返回错误

  

colnames(test)[max.col(test [3,],ties.method =“ first”)]]   [1]不适用   警告信息:   在max.col(test [3,],ties.method =“ first”)中:强制引入的NAs