How to find the keys of the largest values in Hash R? -
i have hash likes example , create hash using hash package.
how can return keys of maximum values in r ?
input hash table :
h<-hash( keys=c(1,4,5,6),values=c(30,25,25,30) ) # <hash> containing 3 key-value pair(s). # 1 : 30 # 4 : 25 # 5 : 25 # 6 : 30
full disclosure: authored , maintain hash
package.
unless have hash many key-value pairs , need performance, standard r vectors names better solution. here 1 example:
v <- c(a = 5, b = 2, c = 3, d = 5) names( v[ v==max(v) ] )
native r vectors outperform hashes until structure grows beyond ~200 key-value pairs. (it been while since benchmarked hash, vector , list lookup performance).
if hash fits solution, answer @bergant solves op's questions, though please understand rather dangerous. converting hash list , using unlist
ignores fact hash values not constrained scalar/atomic values. can r object. consider:
> hash(a = 1:5, b = 2, c = 3, d=5) <hash> containing 4 key-value pair(s). : 1 2 3 4 5 b : 2 c : 3 d : 5
you can decide whether problem application or not.
a simpler, higher performing , more general approach use 'values' function. in simple case values scalar/atomic values, closely mirrors @bergant's solution.
h <- hash(a = 5, b = 2, c = 3, d = 5) val <- values(h) # compare `unlist(as.list(h))` names( val[ val == max(val) ] )
since values returns named list rather unlisted, set more general solution since can select value compare each key value pair:
h <- hash(a = 1:5, b = 2, c = 3, d=5) val <- values(h) # alternate 1: compare min each value val <- sapply(val, max ) # alternate 2: compare first element each value # val <- sapply(val, function(x) x[[1]]) names( val[ val == max(val) ] )
i hope helps.
Comments
Post a Comment