R用条件语句填充矩阵

时间:2018-03-09 18:47:25

标签: r matrix conditional fill

我有一张表格,其中包含有关员工到达和离开时间的数据。时间范围以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)

enter image description here

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

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)

enter image description here

因此,我需要以下列方式填写此矩阵:

enter image description here

为此目的,必须检查条件:

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

换句话说,必须检查是否到达时间等于或晚于矩阵的列中的时间,并且离开的时间等于或早于矩阵的列中的时间。如果条件已满,则在此期间必须将其设为“1”。如果到达时间等于离开时间,则必须将其放入&#34; 1&#34;只有一次。其他单元格必须包含&#34; 0&#34;

提前感谢您的回答!

2 个答案:

答案 0 :(得分:4)

首先,您需要使用0而不是“”来初始化矩阵,因为您希望它们默认为0,是吗?

# initialize your matrix with 0s instead of ""
mat <- matrix( 0, ncol = length(a), nrow=length(b))
colnames(mat) <- c(a) 
rownames(mat) <- c(b)

虽然我不喜欢使用for循环,但这可能是一个合适的案例。使用lapply()返回1的列表。

# mark them on the timesheet
for( i in 1:length(id) ) {
  arrive <- which(colnames(mat) == arrival[i])
  leave <- which(colnames(mat) == leaving[i])
  mat[id[i], arrive : leave] <- 1
}

希望这有帮助!

答案 1 :(得分:2)

[obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7]