I'm new to R. I'm figuring out how to formulate a conditional statement.
If a value in a column is negative, it should add up by 86400.
Any idea?
I'm new to R. I'm figuring out how to formulate a conditional statement.
If a value in a column is negative, it should add up by 86400.
Any idea?
Assuming that your real-word dataset is a data frame, the following will work. You need to specify the column (in this example, column b
) and use ifelse
to evaluate if the value is smaller than 0, if TRUE
, add 86400, otherwise return the original value.
# Create an example data frame
dt <- data.frame(a = "a", b = -3:3)
dt
# a b
# 1 a -3
# 2 a -2
# 3 a -1
# 4 a 0
# 5 a 1
# 6 a 2
# 7 a 3
# Add 86400 to negative value in column `b`
dt$b <- ifelse(dt$b < 0, dt$b + 86400, dt$b)
dt
# a b
# 1 a 86397
# 2 a 86398
# 3 a 86399
# 4 a 0
# 5 a 1
# 6 a 2
# 7 a 3
You can also write the above code as follows.
dt$b <- with(dt, ifelse(b < 0, b + 86400, b))