R 用条件语句填充矩阵

不同的

我有一个表格,其中包含有关员工到达和离开时间的数据。时间范围以 30 分钟的时间间隔给出:

arrival <- c("04:01 - 4:30","00:31 - 1:00","05:01 - 5:30","06:31 - 7:00","08:01 - 8:30") 
leaving <- c("08:31 - 9:00","04:01 - 4:30","06:31 - 7:00","07:31 - 8:00","08:01 - 8:30") 
id <- c("A", "B","C","D","E") 
df <- data.frame(id,arrival,leaving)

在此处输入图片说明

我想知道有多少人同时在工作地点。为此,必须填写以下矩阵:

a <- c("00:00 - 00:30", "00:31 - 1:00",  "01:01 - 1:30",  "01:31 - 2:00",
       "02:01 - 2:30",  "02:31 - 3:00",  "03:01 - 3:30",  "03:31 - 4:00",
       "04:01 - 4:30",  "04:31 - 5:00",  "05:01 - 5:30",  "05:31 - 6:00",  
       "06:01 - 6:30",  "06:31 - 7:00",  "07:01 - 7:30",  "07:31 - 8:00", 
       "08:01 - 8:30",  "08:31 - 9:00") 
b <- c("A", "B","C","D","E") 
mat <- matrix("", ncol = length(a),nrow=length(b)) 
colnames(mat) <- c(a) 
rownames(mat) <- c(b)

在此处输入图片说明

因此,我需要按以下方式填充此矩阵:

在此处输入图片说明

为此,必须检查条件:

If(colnames(mat)>=df$arrival)&(colnames(mat)<=leaving){1}else if(df$arrival = df$leaving){1} else (0)

换句话说,必须检查到达时间是否等于或晚于矩阵列中的时间,离开时间是否等于或早于矩阵列中的时间。如果满足条件,则在此期间必须将其填入“1”。如果到达时间等于离开时间,则只需将“1”置为一次。其他单元格必须包含“0”

预先感谢您的回答!

最大限度
mat<-matrix(0, ncol = length(a),nrow=length(b)) 
colnames(mat)<-a 
rownames(mat)<-b

#Then we find the column that matches the arrival and the one that matches the leaving    

for(i in 1:length(id)) mat[i,which(a==arrival[i]):which(a==leaving[i])]=1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章