具有缺失值的 Cumsum table
Cumsum table with missing value
dt <- data.table(Name =c("A","A","A","A","B","B","B","B","B"),
Number = c(1,3,3,4, 4, 1,1,5,8))
我用这种方式创建了 cumsum table。
library(matrixStats)
tbl <- round(prop.table(table(dt), 1) * 100, 3)
tbl[] <- rowCumsums(tbl)
names(dimnames(tbl)) <- NULL
tbl[] <- paste0(sub("^([^.]+)(\.[^0]).*", "\1\2", tbl), "%")
cumsumtable <- as.data.frame.matrix(tbl)
在原来的 dt 中,缺少 2,6 和 7,所以它没有反映 table。
我想要的精液table是这样的。 2,6和7用之前的百分比填充。
我们可以将 'Number' 转换为 factor
列并指定 levels
dt[, Number := factor(Number, levels = min(Number):max(Number))]
然后 运行 OP 代码
cumsumtable
# 1 2 3 4 5 6 7 8
#A 25% 25% 75% 100% 100% 100% 100% 100%
#B 40% 40% 40% 60% 80% 80% 80% 100%
这也可以在列转换为 factor
之后通过 data.table 方法完成
dcast(dt[, .N,.(Name, Number)][, perc := 100*N/sum(N), Name],
Name ~ Number, value.var = 'perc', fill = 0, drop = FALSE)[,
(2:9) := lapply(Reduce(`+`, .SD, accumulate = TRUE),
function(x) paste0(x, "%")), .SDcols = -1][]
# Name 1 2 3 4 5 6 7 8
#1: A 25% 25% 75% 100% 100% 100% 100% 100%
#2: B 40% 40% 40% 60% 80% 80% 80% 100%
dt <- data.table(Name =c("A","A","A","A","B","B","B","B","B"),
Number = c(1,3,3,4, 4, 1,1,5,8))
我用这种方式创建了 cumsum table。
library(matrixStats)
tbl <- round(prop.table(table(dt), 1) * 100, 3)
tbl[] <- rowCumsums(tbl)
names(dimnames(tbl)) <- NULL
tbl[] <- paste0(sub("^([^.]+)(\.[^0]).*", "\1\2", tbl), "%")
cumsumtable <- as.data.frame.matrix(tbl)
在原来的 dt 中,缺少 2,6 和 7,所以它没有反映 table。
我想要的精液table是这样的。 2,6和7用之前的百分比填充。
我们可以将 'Number' 转换为 factor
列并指定 levels
dt[, Number := factor(Number, levels = min(Number):max(Number))]
然后 运行 OP 代码
cumsumtable
# 1 2 3 4 5 6 7 8
#A 25% 25% 75% 100% 100% 100% 100% 100%
#B 40% 40% 40% 60% 80% 80% 80% 100%
这也可以在列转换为 factor
dcast(dt[, .N,.(Name, Number)][, perc := 100*N/sum(N), Name],
Name ~ Number, value.var = 'perc', fill = 0, drop = FALSE)[,
(2:9) := lapply(Reduce(`+`, .SD, accumulate = TRUE),
function(x) paste0(x, "%")), .SDcols = -1][]
# Name 1 2 3 4 5 6 7 8
#1: A 25% 25% 75% 100% 100% 100% 100% 100%
#2: B 40% 40% 40% 60% 80% 80% 80% 100%