How is a “subset” of a named vector in R?

Suppose I have this named vector in R:

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

How is it most pure to make another named vector with elements 'a' and 'c' only?

If it was a data frame with a column "name" and a column "value", I could use

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

which is good, because a subset can evaluate any logical expression, therefore it is quite flexible.

+4
source share
2 answers

How about this:

foo[c('a','b')]
+5
source

As a side element, avoid "growing" structures in R. Your example can also be written as follows:

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

The subset just loves the way Andrei answers:

foo[c('a','b')]
+2
source

All Articles