0

I want to compute the percentage of the durations a system is deactivated. The activation is given in a column "Active" where 1 means Activation and 0 means deactivation. The observations (rows) correspond to different readings from different systems identified by their "ID". The "Time" of each reading is identified in timestamps. Here is a sample of the data I have in a tibble.

ID Timestamp Active
64 1512743947      1
74 1512743963      1
76 1512743978      1
80 1512743992      0
22 1512744041      1
74 1512744155      1
80 1512744175      1
51 1512744240      1
80 1512744266      0
80 1512744275      1

I followed the response to my question here: Extract change duration in R. But I figured out that the sum of the timestamps difference won't get me to where I want to be. So to be clear, as a response I would like to have the total percentage of time each ID spent deactivated which means between 0 and 1 (not 1 and 0).

ID Percentage
80 67%
MarGa
  • 711
  • 3
  • 10
  • 23

1 Answers1

1

You could try:

library(dplyr)

df %>%
  group_by(ID) %>%
  filter(n_distinct(Active) > 1) %>%
  mutate(time_diff = lead(Timestamp) - Timestamp) %>%
  summarise(
    Percentage = scales::percent(sum(time_diff[Active == 0], na.rm = T) / sum(time_diff, na.rm = T))
  )

Output:

# A tibble: 1 x 2
     ID Percentage
  <int> <chr>     
1    80 67.8%    

Here I presumed on the basis of your output that you'd like to filter out those cases where it is either 100% or 0%.

Otherwise you can do:

df %>%
  group_by(ID) %>%
  mutate(time_diff = lead(Timestamp) - Timestamp) %>%
  mutate(
    Percentage = sum(time_diff[Active == 0], na.rm = T) / sum(time_diff, na.rm = T),
    Percentage = scales::percent(coalesce(Percentage, +(Active == 0) * 1))
  ) %>% 
  distinct(ID, Percentage)

Output:

# A tibble: 6 x 2
# Groups:   ID [6]
     ID Percentage
  <int> <chr>     
1    64 0%        
2    74 0%        
3    76 0%        
4    80 67.8%     
5    22 0%        
6    51 0%       
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • Great ! Thank you. This seems to work. Is there a way to put the result in a file ? – MarGa Feb 28 '19 at 15:26
  • You're welcome! Check functions such as `write.csv`, `write.table`, `fwrite` in `data.table`, for `XLSX` you also have packages such as `xlsx`, `openxlsx`, etc. – arg0naut91 Feb 28 '19 at 15:33