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:

 

The YouTube video will be added soon.

 

Furthermore, you might have a look at the other articles of this homepage:

 

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 my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top