Count Number of Values in Range in R (Example)
In this R article you’ll learn how to get the number of observations within a certain range of values.
The page is structured as follows:
Let’s dig in.
Introducing Exemplifying Data
Have a look at the following example data:
x <- c(3, 1, 6, 5, 6, 3, 4, 4, 8, 2) # Create example vector x # Print example vector # [1] 3 1 6 5 6 3 4 4 8 2 |
x <- c(3, 1, 6, 5, 6, 3, 4, 4, 8, 2) # Create example vector x # Print example vector # [1] 3 1 6 5 6 3 4 4 8 2
Have a look at the previous RStudio console output. It shows that our example data is a numeric vector containing several integer values.
Example: Get Number of Observations in Certain Range Using > & <
In this example, I’ll explain how to count the number of values in a particular range.
For this, we can use the larger than (i.e. “>”) and smaller than (i.e. “<”) operators as shown below:
sum(x > 3 & x < 7) # Count cases in range # [1] 5 |
sum(x > 3 & x < 7) # Count cases in range # [1] 5
The RStudio console returns the result: Five elements of our vector lie in the range between 3 and 7.
Video & Further Resources
Do you need further info on the R programming code of the present article? Then you could watch the following video of the Statistics Globe YouTube channel. In the video, I explain the R programming codes of this tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Besides that, you may have a look at the related tutorials of this website. A selection of articles about ranges and vectors can be found below:
- Count Number of Characters in String
- Select Data Frame Rows where Column Values are in Range
- Count TRUE Values in Logical Vector
- Count Number of Words in Character String
- R Programming Tutorials
On this page, I have illustrated how to count the number of cases in a specific numeric range (i.e. greater than particular value A and smaller than particular value B) in R. Don’t hesitate to let me know in the comments section, if you have additional questions.
Statistics Globe Newsletter