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.
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.
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.
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.
How about this:
foo[c('a','b')]
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With