总结每行dataframe中记录的比例

summarizing the proportion of records in each row of dataframe

我有一个大型数据框,其中一些列只有 'NA' 个值。我想用百分比总结每一行。
比方说:df

user col1 col2 col3 col4 col5 col6
 100   1    1    2   2    1    NA
 200   1    2    3   3    NA   NA
 300   2    3    3   3    2    NA

我想根据成员总数的百分比汇总 user 行。
例如,user:100 占事件 1 的 3/5 和事件 2 的 2/5。

summarized_df:

user event1 event2 event3
100    3/5   2/5    0
200    1/4   1/4    2/4
300    0     2/5    3/5

对每个事件使用百分比也很有用。
我怎样才能在 R 中做到这一点?

这是一个基本的 R 方法,其中包含 applytableprop.table

cbind(dat[1],
      prop.table(t(apply(dat[-1], 1,
                   function(x) table(factor(x, levels=1:3)))), 1))
需要

factor 来确保 table 的输出应用于每一行 returns 每个潜在元素 (1:3),即使一个或多个级别是没有观察到。此处,apply 遍历所有行,returns 计算每个事件,包括事件未发生时的 0。因为每次调用的输出长度相同,applyreturns一个矩阵。我们转置矩阵并使用 prop.table 来计算每一行的每个事件的比例。最后,cbind 将第一列与该矩阵组合,返回具有所需输出的 ​​data.frame。

这个returns

  user    1    2   3
1  100 0.60 0.40 0.0
2  200 0.25 0.25 0.5
3  300 0.00 0.40 0.6

数据

dat <- 
structure(list(user = c(100L, 200L, 300L), col1 = c(1L, 1L, 2L
), col2 = 1:3, col3 = c(2L, 3L, 3L), col4 = c(2L, 3L, 3L), col5 = c(1L, 
NA, 2L), col6 = c(NA, NA, NA)), .Names = c("user", "col1", "col2", 
"col3", "col4", "col5", "col6"), class = "data.frame", row.names = c(NA,-3L))