【问题标题】:Finding difference in time between two data frames using R使用 R 查找两个数据帧之间的时间差异
【发布时间】:2018-08-19 12:30:33
【问题描述】:

我有两个数据框,一个是员工的上班时间,一个是员工的下班时间。两个数据框中的数据都有过去一年大约4000名员工的时间戳(不包括周末/公共假期日期)。每个数据框有 4000 行和 250 列。我想找到员工每天在工作中花费的小时数,基本上我的方法是使用 difftime() 找到两个数据框之间的时间差异函数。我使用了下面的代码,并期望得到一个包含 4000 行和 250 列时间差异的结果数据框,但是数据是在一个列中返回的。我应该如何处理这个问题,以便我可以得到时间差异4000行250列的数据框格式的两个数据框之间?

hours_spent <- as.data.frame(as.matrix(difftime(as.matrix(out_time_data_hrs),as.matrix(in_time_data_hrs),unit='hour')))

输入数据如下所示,

In_time 数据帧

Out_time 数据帧

预期输出

【问题讨论】:

  • 嗨,您能否在问题描述中分享dput(intime_df)dput(outtime_df) 的输出。然后在对象上尝试一些代码会很有帮助。只需在 dput 函数中取两个矩阵的子集。
  • 您想对每个员工和每一天应用一个逻辑(花费的小时数)。您可能需要将数据集重塑为更“整洁”的东西。想象一下像employee iddayin_timeout_time 这样的列,您可以更轻松地查看您必须使用哪些列 group_by 以及要使用哪些列进行计算。
  • 您没有提供理想的输出,但我会根据您目前所展示的内容发布一个示例,希望能帮助您理解逻辑并将其应用于您的案例...... ..
  • 添加了所需的输出

标签: r


【解决方案1】:

这是一个基于您发布的数据的小而简单的示例和一个可能的解决方案:

# example data in_times
df1 = data.frame(`2018-08-01` = c("2018-08-01 10:30:00", "2018-08-01 10:25:00"),
                 `2018-08-02` = c("2018-08-02 10:20:00", "2018-08-02 10:45:00"))
# example data out_times
df2 = data.frame(`2018-08-01` = c("2018-08-01 17:33:00", "2018-08-01 18:06:00"),
                 `2018-08-02` = c("2018-08-02 17:11:00", "2018-08-02 17:45:00"))

library(tidyverse)

# reshape datasets
df1_resh = df1 %>%
  mutate(empl_id = row_number()) %>%   # add an employee id (using the row number)
  gather(day, in_time, -empl_id)       # reshape dataset

df2_resh = df2 %>%
  mutate(empl_id = row_number()) %>%
  gather(day, out_time, -empl_id)

# join datasets and calculate hours spent
left_join(df1_resh, df2_resh, by=c("empl_id","day")) %>%
  mutate(hours_spent = difftime(out_time, in_time))

#   empl_id         day             in_time            out_time    hours_spent
# 1       1 X2018.08.01 2018-08-01 10:30:00 2018-08-01 17:33:00 7.050000 hours
# 2       2 X2018.08.01 2018-08-01 10:25:00 2018-08-01 18:06:00 7.683333 hours
# 3       1 X2018.08.02 2018-08-02 10:20:00 2018-08-02 17:11:00 6.850000 hours
# 4       2 X2018.08.02 2018-08-02 10:45:00 2018-08-02 17:45:00 7.000000 hours

如果您想重新调整为初始格式,可以将其用作最后一段代码:

left_join(df1_resh, df2_resh, by=c("empl_id","day")) %>%
  mutate(hours_spent = difftime(out_time, in_time)) %>%
  select(empl_id, day, hours_spent) %>%
  spread(day, hours_spent)

#   empl_id    X2018.08.01 X2018.08.02
# 1       1 7.050000 hours  6.85 hours
# 2       2 7.683333 hours  7.00 hours

【讨论】:

  • 有道理,会尝试让你知道
【解决方案2】:

只需执行以下操作即可满足我的要求,非常简单

employee_hrs_df <- out_time_data - in_time_data

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多