iobender
iobender

Reputation: 3486

R get max, keyed by another function (like in Python)

In Python, we can do something like

max(stuff, key=lambda x: abs(x.foo))

Which would return the element of stuff which has the member foo with the highest absolute value.

How would I do this in R?

Upvotes: 1

Views: 49

Answers (1)

lebatsnok
lebatsnok

Reputation: 6479

so i suppose stuff must be a list of vectors (or lists) with named elements, something like this:

stuff <- list( first = c(bang=1, qux = 2, foo = 3),
               second = c(bang=6, qux = 0, foo= 100),
               third = c(bang = 1, qux = 7, foo = 0))

you can get the element "foo" using sapply:

sapply(stuff, function(.) .['foo'])

... then find the maximum of it:

which.max(sapply(stuff, function(.) .['foo']))

... and then use it to index your list:

stuff[which.max(sapply(stuff, function(.) .['foo']))]

or with magrittr:

stuff %>% {.[sapply(., "[", "foo") %>% which.max]}

Upvotes: 1

Related Questions