How to Filter Data Conditionally in R
Overview
R is primarily used in statistics, and its ability to select and edit necessary data is unparalleled. Becoming familiar with handling such data can be a bit difficult, but once perfectly mastered, other languages will feel incredibly inconvenient.
In fact, these tips are not much helpful just by reading. (Indeed, the explanations can also be brief in the pursuit of accuracy.) Handling a lot of data and writing various codes naturally leads to proficiency, but avoiding it will not improve one’s skills. If you’re still learning R, it’s recommended to handle even the data that you might think is unnecessary by practicing on your own.
Example
Given an array decreasing from $10$ to $1$ as shown above, the use of logical operators can yield an array of true/false values. The first one selects numbers less than or equal to $5$, and the second one selects only even numbers.
Using such logical arrays allows for very simply selecting data.
Slicing
When slicing, simply inserting an equally long logical array returns an array where true values are kept, and false ones are discarded. In the example, you can see that the numbers in the front have been cut off.
which() function
The which()
function takes a logical array and returns an array of indices. In the example, only the indices corresponding to even numbers are left.
Using this, slicing again allows one to obtain the desired data.
Code
x<-10:1
x<=5
x%%2==0
x[x<=5]
which(x%%2==0)