Assign Value to Elements in Certain Range in R (Example)
In this tutorial, I’ll show how to replace the values in a certain range by a new value in the R programming language.
Table of contents:
Sound good? Let’s dive right into the exemplifying R syntax.
Constructing Example Data
The following data is used as basement for this R tutorial:
x <- 1:10 # Create example vector x # Print example vector # [1] 1 2 3 4 5 6 7 8 9 10
As you can see based on the previous output of the RStudio console, our example data is a numeric vector ranging from 1 to 10.
Example: Assign Value to Elements in Certain Range Using Logical Conditions
In this example, I’ll explain how to assign a different value to all numbers that lie within a particular numerical range.
More precisely, we will exchange all values that are larger than 3 and smaller or equal to 7 by the new value 99.
For this, we can use logical operators and square brackets as shown below:
x_new <- x # Duplicate example vector x_new[x_new > 3 & x_new <= 7] <- 99 # Replace values in range x_new # Print updated vector # [1] 1 2 3 99 99 99 99 8 9 10
Have a look at the previous RStudio console output: We have replaced several numbers by the value 99.
Video, Further Resources & Summary
Have a look at the following video of the Statistics Globe YouTube channel. I explain the topics of this article in the video:
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.
Furthermore, you might have a look at the other articles of this homepage:
- Replace Values in Vector in R
- Replace Values in Factor Vector or Column
- Replace Value of Data Frame Variable Using dplyr Package
- Replace Specific Characters in String
- replace Function in R
- R Programming Language
In this R programming tutorial you have learned how to substitute the numbers in a specific range by a new value.
In this example, we have assigned new values to a vector. However, it would also be possible to use the same kind of R syntax to replace values in data frame columns.
In case you have additional questions, tell me about it in the comments.
Statistics Globe Newsletter