0

I need to get the mean of times in column "ci" [c]lock-[i]n. The data is in character format, e.g. "8:05 AM". I can use the below code to reformat and get the data to a point wherein I can compute a mean:

hrs$ci <- strptime(hrs$ci, format = "%I:%M %p")
mean(hrs$ci)

But for some reason when I try to use dcast to create a table...

hrs <- dcast(hrs, Office ~ Week, value.var = "ci", fun.aggregate = mean)

...it doesn't work and I get this error:

Error in dim(ordered) <- ns : dims [product 900] do not match the length of object [9900]

Any ideas on what I am doing wrong? Or have a suggestion for a better way? In the end I am trying to get the table that the dcast would provide with average clock-in times by week for each office.

Ideally at the end I would have the fraction of a day (i.e. 0.50 = noon) for the time, but I could probably work with alternative formats.

stevenjoe
  • 329
  • 1
  • 4
  • 16

1 Answers1

0

Okay, I think I figured it out. Probably not the most savvy of approaches, but it works!

First I stripped the AM/PM using the below:

hrs$ci <- substr(hrs$ci, 1, 5)

This turned the "08:05 AM" into simply "08:05". Then using another post I converted it to a number:

hrs$ci <- sapply(strsplit(hr$ci, ":"),
    function(x) {
        x <- as.numeric(x)
        x[1]+x[2]/60
    }
)

Then I divided the output by 24 to get the fraction of a day I was looking for:

hrs$ci <- hrs$ci / 24

After which I ran the code I had above:

hrs <- dcast(hrs, Office ~ Week, value.var = "ci", fun.aggregate = mean)

And it works!

Community
  • 1
  • 1
stevenjoe
  • 329
  • 1
  • 4
  • 16
  • Also, in the event that the AM/PM location is not static, you can use `hrs$ci <- sub(" .*", "", hrs$ci)`. – stevenjoe Nov 19 '15 at 22:38