Return value by key

2019-09-24 07:25发布

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

标签: r key
2条回答
Rolldiameter
2楼-- · 2019-09-24 07:51

I think intersect could be useful to you...

vars[ intersect(key,names(vars)) ]
#b a 
#2 1
查看更多
爷的心禁止访问
3楼-- · 2019-09-24 08:03

I believe you simply want vars[key].

查看更多
登录 后发表回答