The sign() function returns the sign of a number: -1 for negative, 0 for zero, and 1 for positive. It’s simpler than it sounds but surprisingly useful in data transformation and conditional processing.
When to Use sign()
You’ll use sign() when:
- Creating direction indicators (positive/negative/neutral)
- Detecting sign changes in time series
- Building directional trading signals
- Data validation and categorization
- Direction-based calculations
Basic Syntax
sign(x)
- x: A numeric value or numeric vector
Return Values
- -1 for negative numbers
- 0 for zero
- +1 for positive numbers
Examples with Explanations
Use sign() Function on Numeric Vector
Let’s apply sign() function on numeric value:
# Define vector
num1 <- c(15,-19,18,-23,27,44,-59)
# Get sign of element
sign(num1)
Output:
[1] 1 -1 1 -1 1 1 -1
As we can see in the output: -19, -23, and -59 have sign -1 because they’re negative, while 15, 18, 27, and 44 have sign 1 because they are positive.
Common Mistakes to Avoid
Mistake 1: Forgetting about zero
# ❌ INCOMPLETE - Treating zero like positive or negative
v <- c(-5, -2, 0, 3, 7)
sign(v) # [1] -1 -1 0 1 1
# ✅ HANDLE ZERO - Remember sign(0) returns 0, not 1
if (sign(x) == 1) # This is FALSE when x = 0!
# Wrong! Zero is neither positive nor negative
Mistake 2: Using sign() instead of direction logic
# ❌ INEFFICIENT - Overcomplicating simple logic
if (sign(v[i] - v[i-1]) > 0) {
print("increasing")
}
# ✅ BETTER - Clearer logic for direction checking
if (v[i] > v[i-1]) {
print("increasing")
}
Mistake 3: Not handling NA values
# ❌ PROBLEM - NA propagates
v <- c(1, -2, NA, 4, -5)
sign(v) # [1] 1 -1 NA 1 -1
# ✅ SOLUTION - Handle NA explicitly
sign(v) %>% replace_na(0) # Replace NA with 0
Mistake 4: Using sign() with non-numeric data
# ❌ ERROR - sign() only works with numeric data
s <- c("a", "b", "c")
sign(s) # Error: non-numeric argument
# ✅ CORRECT - Ensure data is numeric
nums <- as.numeric(c("1", "-2", "3"))
sign(nums) # [1] 1 -1 1
Pro Tips
- Create direction indicator:
sign(v) %>% recode("-1" = "down", "0" = "none", "1" = "up") - Count direction changes:
sum(diff(sign(v)) != 0)shows when direction changes - Detect regime changes: Sign changes in financial data indicate regime shifts
- Combine with other functions:
v * sign(abs(v))returns original values with direction
Real-World Example
# Detecting uptrends and downtrends
price <- c(100, 102, 105, 103, 101, 99, 98, 100, 102, 105)
returns <- diff(price)
# Direction of each return
direction <- sign(returns)
print(direction)
# -1 = down, +1 = up
# Count consecutive up/down days
direction_change <- diff(sign(returns))
# Find reversal points
reversals <- which(direction_change != 0)