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
  • 18,326
  • 38
  • 134
  • 193
  • 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

14

How about this:

foo[c('a','b')]
Andrey Shabalin
  • 4,179
  • 1
  • 18
  • 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,695
  • 6
  • 47
  • 79