# R hack - Bitmasks on vectors to change specific elements

This page is part of a series under tag r-hacks. The series is about a crash course to learn R.

In this note, we are going to learn about a very useful trick to work with vectors and arrays to quickly modify some of the values stored inside them.

Say you have a vector, we can quickly create one by using the c function:

v <- c(2, 4, 1, 0, 2, 0, 5)

Now we want to change some of the elements inside v. What do we do?

### Indexing

If we need to change a single value, we just need its position in the array, so we can use double square brackets to change that value. For example, to change the first 0 into -1, we do:

v[[4]] <- -1
v # Print the vector to see the change
## [1]  2  4  1 -1  2  0  5

The double square brakets let us point one value and change it later by using the assignment operator <-.

### Vector indexing

What if we want to change more elements in a vactor at once? In this case, we can apply a bitmask to the array, and index multiple positions at once. Let’s see it in action first. In our original vector, we want to change all 0s into -1, not just the first one. This is what we do:

v[c(FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE)] <- -1
v # Print the vector to see the change
## [1]  2  4  1 -1  2 -1  5

As we can see, we used single square brackets and a boolean array1 (the bitmask) as input. The input boolean vector must match the original vector v’s length, and it selects the corresponding positions in v which should be changed.

In our example, we have changed the elements in v, whose positions match those of the TRUE elements in the input vector, to -1 in one single line.

Vector indexing for fast vector modification can lead to more advanced scenarios. Take this vector:

v <- c(1, 4, -2, -4, 0, 2, -5, 8)

Say we want to change to 0 all the negative numbers inside v. To do this, we can proceed as follows:

1. Create a bitmask whose length matches v’s, which has TRUE in the corresponding positions where v’s elements are negative and FALSE otherwise.
2. Apply the bitmask to v and assign 0 to the filtered vector.

The above is achieved by the following one liner:

v[sapply(v, function(e) { e < 0 })] <- 0
v # Print the vector to see the change
## [1] 1 4 0 0 0 2 0 8

Function sapply will apply the function on second argument to every element of the input arrray (first argument), returning another vector. By using an inline function, the generated bitmask will select only the values we want to change (in this case, only those that are negative).

Vector indexing can help you quickly modify an array of values! From now on, try to use it every time you need to change multiple values at once basing on a certain condition.

1. A boolean array is a vector of booleans. A boolean is a value which can be TRUE or FALSE.