9

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.

dfrankow
  • 20,191
  • 41
  • 152
  • 214
  • You can still use `subset(foo, names(foo) %in% c('a', 'c'))` but @AndreyShabalin answer is cleaner – dickoa Dec 27 '13 at 04:24
  • Additionally take a look at this question: [In R, why is `[` better than `subset`?](http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset) – Scott Ritchie Dec 27 '13 at 04:39

2 Answers2

15

How about this:

foo[c('a','b')]
Andrey Shabalin
  • 4,389
  • 1
  • 19
  • 18
3

As a sidenote, avoid 'growing' structures in R. Your example can be write like this also:

foo = c(a = 1, b = 2, c = 3)

To subset just do like Andrey's answer:

foo[c('a','b')]
Fernando
  • 7,785
  • 6
  • 49
  • 81