Q:

Creating variables in nested for loop in R

The dataset has cases as rows. Each case has a day it was performed and an operating room where it was performed. It also has a start and end time. I need to create a new variable that stores the information of the order if the cases in a specific operating room are within one day. (i.e. which is the first case of the day and which is the last). I need to save this information in a new variable in the dataset.
Variables are: CASE_ID, DATE, OPER_IN_TIME, OPER_OUT_TIME, OPER_ROOM
OPER_IN_TIME and OPER_OUT_TIME are stored as POSIXct.
DATE is a date variable (format = %Y-%m-%d).
OPER_ROOM is an integer.
I have figured out that I can get the order of the cases in one day in one operating room using dplyr commands:
dataset %>% 
    filter(DATE == "2014-01-02", OPER_ROOM == "20") %>% 
    arrange(OPER_IN_TIME) %>% 
    mutate(ORDER = row_number())

How do I build the nested loop to store this information for each case? I need also to know the last case of the day and store that information also in the case.
Edit: dput()
structure(list(ID = 1:7, OPER_ROOM = c(13L, 12L, 13L, 12L, 13L, 
12L, 13L), OPER_IN_TIME = structure(c(1388644200, 1388643300, 
1388653200, 1388649600, 1388662200, 1388730600, 1388729400), class = c("POSIXct", 
"POSIXt"), tzone = ""), OPER_OUT_TIME = structure(c(1388650800, 
1388647200, 1388658600, 1388658300, 1388665800, 1388737800, 1388745000
), class = c("POSIXct", "POSIXt"), tzone = ""), DATE = structure(c(16072, 
16072, 16072, 16072, 16072, 16073, 16073), class = "Date")), .Names = c("ID", 
"OPER_ROOM", "OPER_IN_TIME", "OPER_OUT_TIME", "DATE"), row.names = c(NA, 
-7L), class = "data.frame")

head()
  ID OPER_ROOM        OPER_IN_TIME       OPER_OUT_TIME       DATE
1  1        13 2014-01-02 08:30:00 2014-01-02 10:20:00 2014-01-02
2  2        12 2014-01-02 08:15:00 2014-01-02 09:20:00 2014-01-02
3  3        13 2014-01-02 11:00:00 2014-01-02 12:30:00 2014-01-02
4  4        12 2014-01-02 10:00:00 2014-01-02 12:25:00 2014-01-02
5  5        13 2014-01-02 13:30:00 2014-01-02 14:30:00 2014-01-02
6  6        12 2014-01-03 08:30:00 2014-01-03 10:30:00 2014-01-03

A:

Here's a solution using the data.table package:
library(data.table)
dt <- data.table(CASE_ID=1:10,
                 DATE=rep(as.Date("2015-01-01")+0:1, 5),
                 OPER_IN_TIME=1:10,
                 OPER_OUT_TIME=11:20,
                 OPER_ROOM=rep(c(1,2),5))

dt[, ORDER := order(-OPER_OUT_TIME), by=list(DATE, OPER_ROOM) ]
dt[, LAST :=  ifelse(ORDER==max(ORDER), T, F), by=list(DATE, OPER_ROOM)]

Just replace the In & Out times with real sortable timestamps...

