# [R] Condition warning: has length > 1 and only the first element will be used

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Oct 15 22:38:42 CEST 2008

```Joe Kaser wrote:
> 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...

OK: help(ifelse), ordinary if doesn't vectorize.

Actually, ifelse does awkward things with classed objects. You might
want something like

sub <- x - y
sub[sub<0] <- x+y

instead. And don't forget to return sub in all cases.

--
O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907

```