在R中对分组数据帧进行过滤时应用规则?

时间:2018-08-05 12:27:44

标签: r dataframe dplyr tidyr

给出以下数据框:

structure(list(press_id = c(1L, 1L, 1L, 1L, 1L), time_state = c("start_time", 
"end_time", "start_time", "end_time", "start_time"), time_state_val = c(164429106667745, 
164429180716697, 164429106667745, 164429180716697, 164429106667745
), timestamp = c(164429106667745, 164429106667745, 164429106667745, 
164429106667745, 164429108669078), acc_mag = c(10.4656808698978, 
10.4656808698978, 10.4656808698978, 10.4656808698978, 10.458666511955
)), .Names = c("press_id", "time_state", "time_state_val", "timestamp", 
"acc_mag"), row.names = c(NA, -5L), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), vars = "press_id", drop = TRUE, indices = list(
    0:4), group_sizes = 5L, biggest_group_size = 5L, labels = structure(list(
    press_id = 1L), row.names = c(NA, -1L), class = "data.frame", vars = "press_id", drop = TRUE, .Names = "press_id"))

我要在过滤时应用“规则”:如果time_state == "start_time",然后检查time_state_interval == min(timestamp),如果它是"end_time",则检查与max(timestamp)的相等性。

如何执行基于规则的filter?我正在尝试使用case_when来做到这一点,但没有产生预期的结果。

  df1 %>% 
  group_by(press_id) %>% 
  mutate(row = row_number(),
         start_time = min(timestamp),
         end_time = max(timestamp)) %>% 
  gather(time_state , time_state_val, -press_id, -row,-timestamp:-vel_ang_mag_avg) %>%
  arrange(press_id, row) %>% 
  select(press_id, time_state, time_state_val, timestamp, acc_mag, vel_ang_mag, -row) %>%
  group_by(press_id, time_state) %>%
  filter(timestamp == case_when(time_state == "start_time" ~ min(timestamp),
                       time_state == "end_time" ~ max(timestamp)))

2 个答案:

答案 0 :(得分:1)

这是您的主意吗?

df1 %>%
  filter((time_state == "start_time" & timestamp == min(timestamp)) | 
         (time_state == "end_time" & timestamp == max(timestamp)))
#   press_id time_state time_state_val timestamp acc_mag
#      <int> <chr>               <dbl>     <dbl>   <dbl>
# 1        1 start_time        1.64e14   1.64e14    10.5
# 2        1 start_time        1.64e14   1.64e14    10.5

答案 1 :(得分:0)

尝试

1200002200000000240000000061D4838D7EA4C680000000000000000000000000005553440000000000C882FD6AB9862C4F90E57E1BA15C248CABAD5BF96840000000000F42407321033BF063167F21FF6C01045B4E2F03F519879B552D2611F0E885E01F08C88D15247446304402202E90609AAFBF4C105408CFF2377D48085879BEE3C7DE57AF125F73926284362A022002D7A487F5929F9A3E1050FC2B5D6AE1DD5384647AD1ABF6D322765F0ABE0A498114C882FD6AB9862C4F90E57E1BA15C248CABAD5BF983148DC6B336C7D3BE007297DB086B1D3483DEA24C2A