0

I have a table like this:

d=structure(list(sample = c("A", "B", "C", "D", "E"), Obs1 = c(10L, 
0L, 11L, 2L, 3L), Obs2 = c(0L, 0L, 2L, 1L, 10L), Obs3 = c(1L, 
1L, 1L, 1L, 10L), Obs4 = c(0L, 11L, 3L, 3L, 3L), Obs5 = c(7L, 
7L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA, -5L
))

For each column i'd like to find row with maximal value in this column to get in result a table like (for my example):

enter image description here

How can i achieve that in R (preferably in Base library).

Denis
  • 315
  • 4
  • 11
  • 2
    You should be able to modify [this previous answer to the question "For each row return the column name of the largest value"](https://stackoverflow.com/questions/17735859/for-each-row-return-the-column-name-of-the-largest-value) to make this work for your question. – Russ Thomas Jul 20 '19 at 23:01

1 Answers1

2

Use apply twice:

data.frame(sample = apply(d[-1], 2, function(x) toString(d[x == max(x), 1])),
           max = apply(d[-1], 2, max))

giving this data.frame:

     sample max
Obs1      C  11
Obs2      E  10
Obs3      E  10
Obs4      B  11
Obs5   A, B   7
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks! That works for me. Let me please a few questions, because your code is too advanced for me? Why `d[-1] not d[,-1]`?I'm wondering, what does that part `d[x == max(x), 1]` do in details? – Denis Jul 21 '19 at 22:50
  • 1
    You can use either d expression. They refer to the same thing. x==max(x) is a logical vector which is TRUE for those positions where x equals the maximum x. Then we take those rows for which it is TRUE and just column 1. – G. Grothendieck Jul 21 '19 at 23:12