user562
user562

Reputation: 51

conditional statement in r

I'm struggling to write an if then statement in R. I have a variable called diel and I would like this variable term to either be "day" or "night" based on the values of a variable called hour. I wrote the code first in SAS and it looks like this:

 length diel $5;
 if 7 <= hour < 17 then diel = 'day';
 if 19 <= hour <= 24 then diel = 'night';
 if 0 <= hour < 5 then diel = 'night';
 run;

As you can see the hours of dusk(17-19) and dawn (5-7) are left out. This is really the problem I'm having in R, I can't figure out how to leave out dusk and dawn. When I write:

dat4$diel <- ifelse ((dat4$hour)< 17, ifelse((dat4$hour) <=7,"day","night"),"night")      

it labels the correct hours of day but labels everything else as night. When I try any other combination like adding another ifelse statement if overwrites the first statement and labels all of hours as day. Thanks for any suggestions!

Upvotes: 0

Views: 278

Answers (2)

agstudy
agstudy

Reputation: 121618

I would do this :

dat = data.frame(hour =0:24)
transform(dat,diel  =ifelse( hour < 17 & hour >=7 , 'day',
                             ifelse(hour>=19 | hour <5,'night',NA)))

     hour  diel
1     0 night
2     1 night
3     2 night
4     3 night
5     4 night
6     5  <NA>
7     6  <NA>
8     7   day
9     8   day
10    9   day
11   10   day
12   11   day
13   12   day
14   13   day
15   14   day
16   15   day
17   16   day
18   17  <NA>
19   18  <NA>
20   19 night
21   20 night
22   21 night
23   22 night
24   23 night
25   24 night

Upvotes: 1

Matthew Lundberg
Matthew Lundberg

Reputation: 42689

Something like this might do:

hour <- 0:24
c('night', NA, 'day', NA, 'night')[findInterval(hour, c(0,5,7,17,19,24), rightmost.closed=TRUE)]
##  [1] "night" "night" "night" "night" "night" NA      NA     
##  [8] "day"   "day"   "day"   "day"   "day"   "day"   "day"  
## [15] "day"   "day"   "day"   NA      NA      "night" "night"
## [22] "night" "night" "night" "night"

Upvotes: 3

Related Questions