10

Using the following two R vectors, I want to extract a subset of valMe using the boolean values in boolMe. In addition, I would like to have two possible outputs, one where the FALSE values in boolMe are ommited from valMe, and one where the FALSE values are replaced by NA. Further illustration of what I want to do in code:

Input

boolMe<-c(FALSE, TRUE, TRUE, TRUE, FALSE, TRUE)
valMe<-1:6

Intended output

NA 2 3 4 NA 6

or

2 3 4 6
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
hhh
  • 50,788
  • 62
  • 179
  • 282
  • In python, I would do it something like this: `>>> a=[False, True, False, False, False, False] >>> b=[10, 11, 12, 13, 14, 15] >>> [bb for (aa,bb) in zip(a,b) if aa] [11]` – hhh Dec 26 '11 at 04:49
  • 2
    In `python3`, `import itertools; list(itertools.compress(b ,a))` – kev Dec 26 '11 at 05:11

2 Answers2

14

You can directly index valMe by using the [ operator:

> valMe[boolMe]
[1] 2 3 4 6

See section 2.7 of the intro manual for more detail.

Chase
  • 67,710
  • 18
  • 144
  • 161
8

Similarly, if you want the NAs:

> valMe[!boolMe] <- NA
> valMe
[1] NA  2  3  4 NA  6

The ! negates the logical boolean so you select the values you want missing. Then, in a touch of R awesomeness, you assign NA to the selected values.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235