Hello,

I've been learning R functions recently and I've come across a problem that
perhaps someone could help me with.

# I have a a chron() object of times

> hours=chron(time=c("01:00:00","18:00:00","13:00:00","10:00:00"))

# I would like to subtract 12 hours from each time element, so I created a
vector of 12 hours (actually, more like a vector of noons)

> less.hours=chron(time=rep("12:00:00",4))

# If I just subtract the two vectors, I get some negative values, as
fractions of a day

> hours-less.hours
[1] -0.45833333  0.25000000  0.04166667 -0.08333333

# I would like those negative values to cycle around and subtract the amount
< 0 from midnight
# That is to say, 01:00:00 - 12:00:00 should be 13:00:00
# because 01:00:00-12:00:00 = -11:00:00, and 24:00:00-11:00:00 = 13:00:00
# It's sort of like going back to the previous day, but without actually
including information about which day it is

# This is what I tried

> test.function=function(x,y) {
+ sub = x-y
+ if(sub<0) x+y
+ }

> test.function(hours,less.hours)
Time in days:
[1] 0.5416667 1.2500000 1.0416667 0.9166667
Warning message:
In if (sub < 0) x + y :
  the condition has length > 1 and only the first element will be used


# My questions are, why does it only use the first element?? Why does it not
apply to all? Also, what happened to the elements where sub>= 0, it looks
like they followed the rules
# of if(sub<0).  I feel like I must not be understanding something rather
basic about how logical expressions operate within R
# Help would be appreciated...

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to