Reputation: 315
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):
How can i achieve that in R
(preferably in Base library
).
Upvotes: 0
Views: 59
Reputation: 270075
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
Upvotes: 2