0

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?

2 Answers2

1

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))
www
  • 38,575
  • 12
  • 48
  • 84
0

Something like:

df[,'col']=df[,'col']+ifelse(df[,'col']<0,86400,0)
ags29
  • 2,621
  • 1
  • 8
  • 14