0

I have a list time_info_summary

> time_info_summary
$mon_from_time

0700 0800 
  14  388 

$mon_to_time

1800 1830 2000 2100 2200 2300 
1    1     60  121  214    5 

$tue_from_time

0700 0800 
14   388 

$tue_to_time

1800 1830 2000 2100 2200 2300 
1    1    60   121  214    5 

It is a list of tables.

> typeof(time_info_summary)
[1] "list"

It contains the time (like for "mon_from_time" it is 0700 for which count is 14 and for 0800 count is 388). I want to calculate the weighted average of time for each of the item of list. i.e., what is the weighted average for "mon_from_time" ((0700*14 +0800*388)/402 = 0796) and so on...how can I do this

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Archit gupta
  • 147
  • 1
  • 2
  • 11
  • See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 for how to make the example reproducible (probably just using `dput`). `rbindlist(lapply(L, as.data.frame), idcol="var")` should get you halfway there if you're using data.table (per your tags). – Frank May 15 '17 at 12:01

1 Answers1

0

This should work even though it's not very elegant.

> tabs<- apply(time_info_summary, 2, table)
> lapply(tabs, function(x) weighted.mean(as.numeric(names(x)), x)/100)
$mon_from_time
[1] 7.965174

$mon_to_time
[1] 10.85348

$tue_from_time
[1] 7.965174

$tue_to_time
[1] 10.85348
Yannis Vassiliadis
  • 1,719
  • 8
  • 14
  • Converting times to numeric is probably not what's wanted. Instead, should convert to seconds since midnight or similar, I guess. Data.table has `ITime` for this, fwiw. – Frank May 15 '17 at 14:31