Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'subset' a named vector in R?

Tags:

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.

like image 318
dfrankow Avatar asked Dec 27 '13 04:12

dfrankow


People also ask

How do you subset an object in R?

Method 2: Subsetting in R Using [[ ]] Operator [[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.

How do I extract elements from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.

How do I subset a list in R?

To subset lists we can utilize the single bracket [ ] , double brackets [[ ]] , and dollar sign $ operators. Each approach provides a specific purpose and can be combined in different ways to achieve the following subsetting objectives: Subset list and preserve output as a list. Subset list and simplify output.


2 Answers

How about this:

foo[c('a','b')]
like image 56
Andrey Shabalin Avatar answered Oct 14 '22 01:10

Andrey Shabalin


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')]
like image 26
Fernando Avatar answered Oct 14 '22 00:10

Fernando