How to 'subset' a named vector in R?

Viewed 5225

Suppose I have this named vector in R:

foo=vector()
foo['a']=1
foo['b']=2
foo['c']=3

How do I most cleanly make another named vector with only elements 'a' and 'c'?

If this were a data frame with a column "name" and a column "value" I could use

subset(df, name %in% c('a', 'b'))

which is nice because subset can evaluate any boolean expression, so it is quite flexible.

2 Answers
Related