[R] Splitting a time + duration into a series of periods
Phil Spector
spector at stat.berkeley.edu
Fri Sep 24 21:51:40 CEST 2010
Travers -
R's date/time abilities are pretty powerful -- you shouldn't have to
resort to outside programs. Here's how I'd approach the problem:
> dat = read.csv(textConnection('user, login_time, session_min
+ alice, 2010/01/01 10:00, 145
+ bob, 2010/01/01 11:00, 30
+ '),stringsAsFactors=FALSE)
> dat$login_time = as.POSIXct(dat$login_time)
> dat$login_end = dat$login_time + 60 * dat$session_min
> tms = seq(as.POSIXct('2010/01/01 10:00'),
+ as.POSIXct('2010/01/01 12:30'),by=30*60)
> data.frame(time=tms,count=sapply(tms,
+ function(tm)sum(dat$login_time <= tm & dat$login_end > tm)))
time count
1 2010-01-01 10:00:00 1
2 2010-01-01 10:30:00 1
3 2010-01-01 11:00:00 2
4 2010-01-01 11:30:00 1
5 2010-01-01 12:00:00 1
6 2010-01-01 12:30:00 0
Hope this helps.
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Fri, 24 Sep 2010, Travers Naran wrote:
> Hi all,
>
> Here's what I have. I have a list of log-in times for users and how
> long their sessions were.
>
> user, login_time, session_min
> alice, 2010/01/01 10:00, 145
> bob, 2010/01/01 11:00, 30
>
> What I want to do is create a bar chart showing, in 1/2 hour segments,
> the number of users logged in at the same time. For example:
>
> 10:00 1
> 10:30 1
> 11:00 2
> 11:30 1
>
> The only way I can do this now is to send the data through a Perl
> script to generate raw data like:
>
> alice, 2010/01/01, 10:00
> alice, 2010/01/01, 10:30
> alice, 2010/01/01, 11:00
> ...
> bob, 2010/01/01, 11:00
>
> I've looked through the man pages for a couple hours now, and I can't
> find a better of way of doing this directly in R. Any help or
> pointers? Thanks in advance.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list