简体   繁体   中英

R Select row with min value greater than zero using dplyr

Attempting to group rows by x and selecting row with the minimum value greater than zero

 x  Start Time      End Time        Time_Diff
 A  01-01-17 0:14   01-01-17 0:14   3
 A  01-01-17 0:14   01-01-17 21:51  77817
 B  01-01-17 15:59  01-01-17 7:22   -31042
 B  01-01-17 15:59  01-01-17 16:25  1574

Attempted:

df1 <- df %>%
    group_by(x) %>%
    slice(which.min(as.numeric(Time_Diff)))

However, it returns the negative values. This is the solution I'm expecting. Any help will be appreciated.

 x  Start Time      End Time        Time_Diff 
 A  01-01-17 0:14   01-01-17 0:14   3
 B  01-01-17 15:59  01-01-17 16:25  1574

I think this also works

df2 <- df %>%
  group_by(x) %>%
  filter( Time_Diff > 0 ) %>%
  arrange(desc(as.numeric(Time_Diff))) %>%
  slice(n = n())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM