Return value by key

2019-09-24 07:55发布

问题:

Is there a shorter way to return the values by key in the order, which is given by elements of key?

vars<-c("a"=1,"b"=2)
key<-c("b","a")
ret<-c()
for(k in key)
ret<-c(ret,vars[names(vars) %in% k])
ret

回答1:

I believe you simply want vars[key].



回答2:

I think intersect could be useful to you...

vars[ intersect(key,names(vars)) ]
#b a 
#2 1


标签: r key