R 中停用持续时间的百分比

Percentage of Duration of deactivation in R

我想计算系统停用持续时间的百分比。 激活在 "Active" 列中给出,其中 1 表示激活,0 表示停用。观察结果(行)对应于由 "ID" 识别的不同系统的不同读数。每个读数的 "Time" 在时间戳中标识。 这是我在 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

我在这里关注了对我的问题的回答:。但我发现时间戳差异的总和不会让我到达我想去的地方。明确地说,作为回应,我希望每个 ID 停用的总时间百分比,这意味着在 0 和 1 之间(而不是 1 和 0)。

ID Percentage
80 67%

你可以试试:

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))
  )

输出:

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

在此,我根据您的输出推测您希望过滤掉 100% 或 0% 的情况。

否则你可以这样做:

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)

输出:

# 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%