我有两个数据框,一个是员工的上班时间,另一个是员工的外出时间。两个数据框中的数据在过去一年中大约有4000名员工的时间戳(不包括周末/公共假期)日期)。每个数据帧有4000行和250列。我想找到一个员工每天在工作上花费的小时数,基本上我的方法是使用difftime()查找两个数据帧之间的时间差function.i使用下面的代码,并期望得到包含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数据帧
超时数据帧
预期产量
答案 0 :(得分:2)
这是一个基于您发布的数据和可能的解决方案的小而简单的示例:
# 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
答案 1 :(得分:0)
只需做下面的事情就可以满足我的要求
body,html {
height: 100%;
background:#333A4D;
}
.navbar{
padding: 10px;
background: #F3B0B6;
}
.nav-link{
font-size: 25px;
line-height: 32px;
color: #F3B0B6;
}
.nav-item { margin-left: 1rem; }
.list-inline-item{ margin-left: 1rem; }
.jumbotron{ background: none; }
.text-border{
display: block;
height: 1px;
border: 0;
border-top: 4px solid #F3B0B6;
}
.lead{
text-transform: uppercase;
color: #F3B0B6;
font-size: 25px;
line-height: 31px;
}
.custom-form-container{margin-top: 5rem;}
.custom-form{
background: green;
padding: 60px 82px 60px 82px;
border-radius: 10px;
-webkit-box-shadow: 0px 3px 6px -4px #000000;
box-shadow: 0px 3px 6px -4px #000000;
}
.custom-form label{
font-size: 25px;
line-height: 32px;
color: #F3B0B6;
margin-left: 1rem;
}
.custom-form .btn{
float: right;
margin-top: 3rem;
margin-right: -3rem;
font-size: 25px;
line-height: 32px;
color: #F3B0B6;
background: none;
}
.custom-form .form-control{
height: 40px;
border: 1px solid rgba(0, 0, 0, 0.15);
background: rgba(0, 0, 0, 0.1);
}