I have such type of data:
Date Status ID
23-1-2010 11:40 in 321
23-1-2010 11:53 out 321
9-1-2010 12:11 in 356
9-1-2010 12:18 out 356
23-1-2010 11:37 in 356
23-1-2010 11:5 out 356
5-2-2010 13:14 in 398
5-2-2010 13:30 out 398
10-3-2010 9:30 in 398
13-3-2010 11:50 out 377
16-3-2010 10:30 in 377
16-3-2010 11:00 out 377
20-3-2010 12:09 in 377
20-3-2010 12:30 out 377
The data describes customers who visited a supermarket in a certain date and time. The customers are identified by their ID and their status is also specified.
I want to calculate the time a customer spent in the supermarket on different days. The problem I have with the data is for some customers only the entrance time or exit time is recorded. I have cleared the customers who visited once and either in or out status is missing but I still have some of them who visited more than once and the in/out is missing.
I have tried this
#create an empty data frame
TimeSpent<-rep(NA,length(df$ID))
ID<-rep(NA,length(df$ID))
Tspent<-data.frame(TimeSpent,ID)
#compute the time spent time
for(i in 1:length(df$Date - 1))
{
if(isTRUE(df$Status[i] == "in" && df$Status[i+1] == "out"))
{
Tspent$ID[i] <- df$ID[i]
Tspent$TimeSpent[i] <- difftime(df$Date[i+1] - df$Date[i])
} else if(isTRUE(df$Status[i+1] == "in" && df$Status[i+2] == "out"))
{
Tspent$ID[i] <- df$ID[i+1]
Tspent$TimeSpent[i] <- difftime(df$Date[i+2] - df$Date[i+1])
} else
{
Tspent$ID[i] <- df$ID[i+2]
Tspent$TimeSpent[i] <- difftime(df$Date[i+3] - df$Date[i+2])
}
i<-i+1
}
and I get this error: Error in as.POSIXct.default(time1) : do not know how to convert 'time1' to class "POSIXct"
Does anyone knows how to correct my code or any alternative solution? Thanks in advance!