Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop a double-conditional over a vector

Halloo! I’ve hit a snag trying to automate an ifelse statement with two conditions… I’ve generated a fake value for every minute in a day and want to group values by intervals – hourly, every 5 mins, every twenty, whathaveyou – but the only way I’ve been able thus far to group by these intervals is brute force:

d$hourly <- ifelse(d$t >= 0 & d$t <= 60, 0, 
       ifelse(d$t > 60 & d$t <= 120, 1, 
       ifelse(d$t > 121 & d$t <= 180, 2, 
       ifelse(d$t > 180 & d$t <= 240, 3, 
       ifelse(d$t > 240 & d$t <= 300, 4,
       ifelse(d$t > 300 & d$t <= 360, 5,
       ifelse(d$t > 360 & d$t <= 420, 6, 
       ifelse(d$t > 420 & d$t <= 480, 7, 
       ifelse(d$t > 480 & d$t <= 520, 8,
       ifelse(d$t > 520 & d$t <= 600, 9,
       ifelse(d$t > 600 & d$t <= 660, 10,
       ifelse(d$t > 660 & d$t <= 720, 11, 
       ifelse(d$t > 720 & d$t <= 780, 12, 
       ifelse(d$t > 780 & d$t <= 840, 13, 
       ifelse(d$t > 840 & d$t <= 900, 14, 
       ifelse(d$t > 900 & d$t <= 960, 15,
       ifelse(d$t > 960 & d$t <= 1020, 16,
       ifelse(d$t > 1020 & d$t <= 1080, 17,                                     
       ifelse(d$t > 1080 & d$t <= 1140, 18, 
       ifelse(d$t > 1140 & d$t <= 1200, 19,
       ifelse(d$t > 1200 & d$t <= 1260, 20, 
       ifelse(d$t > 1260 & d$t <= 1320, 21,                                     
       ifelse(d$t > 1320 & d$t <= 1380, 22, 
       ifelse(d$t > 1380 & d$t <= 1440, 23, NA))))))))))))))))))))))))

presumably, there is something I am not understanding about for(i in 1:nrow) or other looped functions. Is there a cleaner way to loop conditionals over a vector?

Many thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In this case you can just divide by 60 can’t you?

d  <- data.frame(t = seq(0:1439))

d$hourly  <- floor(d$t/60)

head(d)
#   t hourly
# 1 1      0
# 2 2      0
# 3 3      0
# 4 4      0
# 5 5      0
# 6 6      0

tail(d)
#         t hourly
# 1435 1435     23
# 1436 1436     23
# 1437 1437     23
# 1438 1438     23
# 1439 1439     23
# 1440 1440     24
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading