我需要按照每天的通话次数来获取累计客户。
示例表将是:
> data
dia cli llam elegidos cumllam
1 1-11 a 1 1 1
2 3-11 a 1 1 2
3 1-11 b 2 1 2
4 2-11 b 1 1 3
5 2-11 c 2 0 2
正如您所看到的,客户端在第2-11天没有打电话,因此组合客户端a + day 2-11并未出现在表格中。如果我跑:
series<-data.frame(dcast(data, elegidos+dia~cumllam , length))
我明白了:
> series
elegidos dia X1 X2 X3
1 0 2-11 0 1 0
2 1 1-11 1 1 0
3 1 2-11 0 0 1
4 1 3-11 0 1 0
但是如果你考虑直到第二天一次调用了多少个客户端,那么客户端应该出现并且它不会因为我在组合客户端的前一个表中没有行a和第2-11天。
该表应如下所示:
elegidos dia X1 X2 X3
1 0 2-11 0 1 0
2 1 1-11 1 1 0
3 1 2-11 1 0 1
4 1 3-11 0 1 1
x1是收到直到并且包括行中某天正好1次通话的客户端数量。
x2是直到并且包括行中某天正好接听2个电话的客户端数量。
等等。
解释是:
有没有办法对每天进行累积计数,而无需为每个客户日组合创建一行?
感谢。
答案 0 :(得分:1)
试试这个:
dat1 <-data[!!data$elegidos,]
dat2 <- expand.grid(dia=sort(unique(dat1$dia)), cli=unique(dat1$cli))
dat3 <- merge(data,dat2, all=TRUE)
dat3N <- dat3[with(dat3, order( cli, dia)),]
library(zoo)
dat3N[,c('elegidos', 'cumllam')] <- lapply(dat3N[,
c('elegidos', 'cumllam')], na.locf)
library(reshape2)
dcast(dat3N, elegidos+dia~cumllam, length, value.var='cumllam')
# elegidos dia 1 2 3
#1 0 2-11 0 1 0
#2 1 1-11 1 1 0
#3 1 2-11 1 0 1
#4 1 3-11 0 1 1
您也可以在data.table
library(data.table)
DT <- data.table(data)
setkey(DT, dia, cli)
DT1 <- rbind(DT[!!elegidos, CJ(dia=unique(dia),
cli=unique(cli))], DT[elegidos==0, 1:2, with=FALSE])
nm1 <- c('elegidos', 'cumllam')
#There is also a roll option but unfortunately I couldn't get it right here.
# So, I am using na.locf from zoo.
DT2 <- DT[DT1[order(cli, dia)]][,(nm1):= lapply(.SD, na.locf), .SDcols=nm1]
dcast.data.table(DT2, elegidos+dia~cumllam, length, value.var='cumllam')
# elegidos dia 1 2 3
#1: 0 2-11 0 1 0
#2: 1 1-11 1 1 0
#3: 1 2-11 1 0 1
#4: 1 3-11 0 1 1
data <- structure(list(dia = c("1-11", "3-11", "1-11", "2-11", "2-11"
), cli = c("a", "a", "b", "b", "c"), llam = c(1L, 1L, 2L, 1L,
2L), elegidos = c(1L, 1L, 1L, 1L, 0L), cumllam = c(1L, 2L, 2L,
3L, 2L)), .Names = c("dia", "cli", "llam", "elegidos", "cumllam"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))