dfrankow
dfrankow

Reputation: 21469

How to 'subset' 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 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.

Upvotes: 9

Views: 6958

Answers (2)

Fernando
Fernando

Reputation: 7905

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')]

Upvotes: 3

Andrey Shabalin
Andrey Shabalin

Reputation: 4614

How about this:

foo[c('a','b')]

Upvotes: 15

Related Questions