使用sapply时包括行名

时间:2019-06-26 22:20:41

标签: r matrix sapply rowname

我正在尝试使用sapply将函数应用于数据框。函数是Erlang C计算,是我在研究时遇到的一个站点中发现的。我遇到的麻烦是如何包括与输出关联的行名。我希望结果包括下面示例中的“ wkday”和“ grpnum”中的行名。我尝试了看过的样品,但是没有运气。

thank you in advance

带有代码的示例数据:

wkday <-c("Mon","Tue","Wed","Thur","Fri","Sat","Sun","Sat","Mon")
grpnum <-c(2,2,1,3,5,4,8,9,6)
p1 <- c(1,5,6,15,15,6,2,10,35)
p2 <- c(2,3,4,5,8,25,7,20,3)
testdf <- data.frame(wkday,grpnum,p1,p2)

## Erlang Calculation ##

dur = 600
tgt = 300
gostgt = 75

intensity <- function(rate, duration = dur, interval = 60) {
(rate / (60 * interval)) * duration
}

erlang_c <- function(agents, rate, duration, interval = 60) {
int <- intensity(rate, duration, interval)
erlang_b_inv <- 1
for (i in 1:agents) {
erlang_b_inv <- 1 + erlang_b_inv * i / int
}
erlang_b <- 1 / erlang_b_inv
agents * erlang_b / (agents - int * (1 - erlang_b))
}

service_level <- function(agents, rate, duration, target, interval = 
60) {
pw <- erlang_c(agents, rate, duration, interval)
int <- intensity(rate, duration, interval)
1 - (pw * exp(-(agents - int) * (target / duration)))
}

resource <- function(rate, duration = dur, target = tgt, gos_target = 
gostgt, interval = 60) {
agents <-round(intensity(rate, duration, interval) + 1)
gos <- service_level(agents, rate, duration, target, interval)
while (gos < gos_target * (gos_target > 1) / 100) {
agents <- agents + 1
gos <- service_level(agents, rate, duration, target, interval)
}
return(agents)
}

m1 <- as.matrix(sapply(p1,resource))
m2 <- as.matrix(sapply(p2,resource))
cbind(m1,m2)

current output:
     [,1] [,2]
 [1,]    1    1
 [2,]    2    2
 [3,]    2    2
 [4,]    4    2
 [5,]    4    3
 [6,]    2    6
 [7,]    1    3
 [8,]    3    5
 [9,]    8    2

desired output:
     [,1] [,2]
 Mon    1    1
 Tue    2    2
 Wed    2    2
 Thur   4    2
 Fri    4    3
 Sat    2    6
 Sun    1    3
 Sat    3    5
 Mon    8    2

0 个答案:

没有答案