编写一个函数来按比例过滤和汇总数据 table

Writing a function to filter and summarize data into proportion table

我想创建一个大比例table,涉及根据一列过滤掉某些值并输出table中等于0和大于0的值的比例。这是数据框 (df) 的示例:

     ID   a   b   c   d   e   f   g
1     1   1   2   3   0   4   5   A 
2     2   0   0   1   0   2   0   A
3     3   1   5   2   1   0   0   B
4     4   5   1   2   0   1   1   B
5     5   2   0   1   0   0   0   C
...

据此,我想得出 b=0 或 b>0 IF 列 a>0 的比例。供您参考,我可以使用以下代码获取此信息:

prop.table(table(df$b[df$a>0]!=0))*100

但是,我想对 c 和 d 列以及 e 和 f 列执行相同的操作(相同类型的模式,以便在 c=0 和 e=0 时过滤掉那些 >0和 =0 比例分别为 d 和 f)。此外,我希望将此输出全部合并到一个 table 中。可能看起来像这样:

      b.perc   d.perc   f.perc
TRUE   75.00    20.00    66.67
FALSE  25.00    80.00    33.33

感谢任何帮助。另外,我想计算 G 列中列出的各组的 TRUE 百分比,给我这样的输出:

      b.perc   d.perc   f.perc
A     100.00    0.00     50.00
B     100.00   50.00    100.00
C     0.00      0.00      0.00

我们对备用列进行子集化,将每个集合用作 mapply 的输入,根据 OP post[中提到的条件获得 tableprop.table

out <- round(mapply(function(x, y) prop.table(table(x[y > 0] != 0)) * 100,
          df[c(FALSE, TRUE)], df[c(TRUE, FALSE)]), 2)
colnames(out) <- paste0(colnames(out), ".perc")
out
#      b.perc d.perc f.perc
#FALSE     25     80  33.33
#TRUE      75     20  66.67

如果我们只对 TRUE 百分比感兴趣,那么我们也可以使用 colMeans

colMeans((df[c(FALSE, TRUE)] * NA^!(df[c(TRUE, FALSE)] > 0)) != 0, na.rm = TRUE)
#       b         d         f 
#0.7500000 0.2000000 0.6666667 

数据

df <- structure(list(a = c(1L, 0L, 1L, 5L, 2L), b = c(2L, 0L, 5L, 1L, 
0L), c = c(3L, 1L, 2L, 2L, 1L), d = c(0L, 0L, 1L, 0L, 0L), e = c(4L, 
2L, 0L, 1L, 0L), f = c(5L, 0L, 0L, 1L, 0L)), class = "data.frame",
row.names = c("1", 
"2", "3", "4", "5"))