antonio
antonio

Reputation: 77

How can I use a loop in function within ddply

I would like to sum a column of time differences diff for 14 different users when these time differences occurred in some fixed time events(number of events=108).
here the head of the first dataframe with times differences 'diff`, this dataframe contains 152171 rows:

head(hope)
                times        users signal mode diff
1 2014-01-13 00:00:16 00250902DC7D   true   ON   31
2 2014-01-13 00:00:47 00250902DC7D   true   ON   31
3 2014-01-13 00:01:18 00250902DC7D   true   ON   30
4 2014-01-13 00:01:48 00250902DC7D   true   ON   31
5 2014-01-13 00:02:19 00250902DC7D   true   ON   31
6 2014-01-13 00:02:50 00250902DC7D   true   ON   31 

The second dataframe with 108 different times ranges (nrow=108)is:

head(events)
          start                 end
1 2014-01-14 06:30:00 2014-01-14 07:00:00
2 2014-01-14 10:30:00 2014-01-14 11:00:00
3 2014-01-14 18:00:00 2014-01-14 18:30:00
4 2014-01-14 22:30:00 2014-01-14 22:59:00
5 2014-01-15 02:30:00 2014-01-15 02:59:00
6 2014-01-15 09:00:00 2014-01-15 09:30:00  

If I select one event manually (I chose by chance the 12th event..), I able to count the timedifferences (diff) within the 12th event and it works...but I have 108 different evevnts...

hope1 <- hope[hope$mode=="ON" & hope$times>events[12,1] & hope$times<events[12,2],]
ddply(hope1,.(users),summarize,sum=sum(diff))  
         users  sum
1 00250902DC7D 1857
2 00250902FA92 1857
3 00250902FB05 1857
4 002509030C41 1857
5 002509030E53 1857  

*ok perfect, BUT ONLY FOR ONE EVENT*

If I want to do it for 108 different events, should I use a loop maybe?

I tried something like the following code, but I/it failed...:

> for (i in 1:108)
+ hope5 <- data.frame(hope[hope$mode=="ON" & hope$times>events[i,1] & hope$times<events[i,2],])  
ddply(hope5,.(users),summarize,sum=sum(diff))

Could you help me please?

I would like to get an output like this one:

> pippo

                   00250902DC7D 00250902FA92 00250902FB05
2014-01-14 06:30:00           35           32          335
2014-01-14 10:30:00           38           31          338
2014-01-14 18:00:00           49           29          429
2014-01-14 22:30:00           48          438           48
2014-01-15 02:30:00           29           29          289

Upvotes: 1

Views: 223

Answers (1)

Victorp
Victorp

Reputation: 13856

You could work with list and lapply :

hopeN <- lapply(1:nrow(events), function(i) hope[hope$mode=="ON" & hope$times>events[i,1] & hope$times<events[i,2],])

result <- lapply(1:length(hopeN), function(i) ddply(hopeN[[i]],.(users),summarize,sum=sum(diff)))

The result is a list of data.frames.

Upvotes: 1

Related Questions