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:
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.
Subscribe to the Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.






