Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting a vector using another boolean vector in R

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
like image 395
hhh Avatar asked Dec 26 '11 04:12

hhh


People also ask

How to subset A vector in R?

By using this notation we can subset the vector by index, name, value, by checking the condition, by range e.t.c. R also provides a subset () function to subsetting the vector by name and index. The subset () is a generic function that can be also used to subset dataframe and matrix.

How do you subset A vector in MATLAB?

There are six ways to subset atomic vectors. There are three subsetting operators, [ [, [, and $. Subsetting operators interact differently with different vector types (e.g., atomic vectors, lists, factors, matrices, and data frames).

How do I subset atomic vectors in Python?

There are six ways to subset atomic vectors. There are three subsetting operators, [ [, [, and $. Subsetting operators interact differently with different vector types (e.g., atomic vectors, lists, factors, matrices, and data frames). Subsetting can be combined with assignment. Subsetting is a natural complement to str ().

Is it possible to subset matrices and arrays in R?

Because both matrices and arrays are just vectors with special attributes, you can subset them with a single vector, as if they were a 1D vector. Note that arrays in R are stored in column-major order:


2 Answers

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.

like image 187
Chase Avatar answered Oct 18 '22 06:10

Chase


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.

like image 42
Ari B. Friedman Avatar answered Oct 18 '22 05:10

Ari B. Friedman