R get max, keyed by another function (like in Python) -
in python, can
max(stuff, key=lambda x: abs(x.foo)) which return element of stuff has member foo highest absolute value.
how in r?
so suppose stuff must list of vectors (or lists) named elements, 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 element "foo" using sapply:
sapply(stuff, function(.) .['foo']) ... find maximum of it:
which.max(sapply(stuff, function(.) .['foo'])) ... , use index list:
stuff[which.max(sapply(stuff, function(.) .['foo']))] or magrittr:
stuff %>% {.[sapply(., "[", "foo") %>% which.max]}
Comments
Post a Comment