You can use the sign() function in base R to return the sign of each element in a vector.
This function uses the following basic syntax:
sign(x)
where:
- x: A numeric vector
The function will return:
- -1: If a value is negative
- 0: If a value is zero
- 1: If a value is positive
The following examples show how to use the sign() function in different scenarios.
Example 1: Use sign() with Vector
The following code shows how to use the sign() function to display the sign of each value in a numeric vector:
#define vector of values
x #return sign of each element in vector
sign(x)
[1] -1 0 1
Here’s how to interpret the output:
- The first value is -1 since the first value in the vector is negative.
- The second value is 0 since the second value in the vector is zero.
- The third value is 1 since the third value in the vector is positive.
Example 2: Use sign() with Data Frame Column
The following code shows how to use the sign() function to display the sign of each value in a column of a data frame:
#create data frame df frame(x=c(0, 1.4, -1, 5, -4, 12), y=c(3, 4, 3, 6, 10, 11)) #view data frame df x y 1 0.0 3 2 1.4 4 3 -1.0 3 4 5.0 6 5 -4.0 10 6 12.0 11 #view sign of each value in column x sign(df$x) [1] 0 1 -1 1 -1 1
Example 3: Use sign() to Create New Data Frame Column
Suppose we have the following data frame in R:
#create data frame df frame(x=c(0, 1.4, -1, 5, -4, 12), y=c(3, 4, 3, 6, 10, 11)) #view data frame df x y 1 0.0 3 2 1.4 4 3 -1.0 3 4 5.0 6 5 -4.0 10 6 12.0 11
The following code shows how to use the sign() function to create a new column called ‘z’ whose values are dependent on the values in the existing column ‘x’:
#create new column 'z' based on sign of values in column 'x' df$z negative', ifelse(sign(x) == 0, 'zero', 'positive'))) #view updated data frame df x y z 1 0.0 3 zero 2 1.4 4 positive 3 -1.0 3 negative 4 5.0 6 positive 5 -4.0 10 negative 6 12.0 11 positive
Notice that the values in column ‘z’ correspond to the sign of the values in column ‘x’.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use the dim() Function in R
How to Use the transform() Function in R
How to Use the sweep() Function in R