How to Set Negative Values to 0 in R (Example Code)

This tutorial explains how to set negative values to zero in R programming.

Introduction of Example Data

x <- -5:5                         # Example vector in R
x                                 # Display example vector in RStudio console
# [1] -5 -4 -3 -2 -1  0  1  2  3  4  5

Example: Set Negative Values to Zero Using “Smaller Than” Operator

x[x < 0] <- 0                     # Replace negatives
x                                 # Print new vector to RStudio console
#  [1] 0 0 0 0 0 0 1 2 3 4 5

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.
You need to agree with the terms to proceed

Menu
Top