Time difference between rows in R dplyr, different units

前端 未结 2 1410
野趣味
野趣味 2021-01-19 16:49

Here is my example. I am reading the following file: sample_data

library(dplyr)

txt <- c(\'\"\",  \"MDN\",                  \"Cl_Date\"\',
          \'\"         


        
相关标签:
2条回答
  • 2021-01-19 17:31
    ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
      mutate(time_diff_2 = as.numeric(Cl_Date-lag(Cl_Date), units = 'mins'))
    

    Convert the time difference to a numeric value. You can use units argument to make the return values consistent.

    0 讨论(0)
  • 2021-01-19 17:36

    According to @hadley here, the solution is to use lubridate instead of relying on base R.

    This would be something like:

    ts %>% 
      group_by(MDN) %>% 
      arrange(Cl_Date) %>%
      mutate(as.duration(Cl_Date %--% lag(Cl_Date)))
    
    0 讨论(0)
提交回复
热议问题