首页 > 解决方案 > 如何从列表中生成百分比的数据框摘要

问题描述

我的数据由一个列表组成,描述了 6 个类别(random_sequence_generation 等)的“H”、“L”和“U”的频率。

我想生成一个数据框,其中每一行代表观察到的“H”、“L”和“U”的百分比,即

random_sequence_generation  6.7 63.3 30.0
allocation_concealment      0.0 43.3 56.7
...                         ...

给定数据:

   dat <- list(random_sequence_generation = structure(c(H = 2L, L = 19L, 
    U = 9L), .Dim = 3L, .Dimnames = structure(list(c("H", "L", "U"
    )), .Names = ""), class = "table"), allocation_concealment = structure(c(L = 13L, 
    U = 17L), .Dim = 2L, .Dimnames = structure(list(c("L", "U")), .Names = ""), class = "table"), 
        blinding_of_participants = structure(c(H = 30L), .Dim = 1L, .Dimnames = structure(list(
            "H"), .Names = ""), class = "table"), blinding_of_personnel = structure(c(H = 28L, 
        U = 2L), .Dim = 2L, .Dimnames = structure(list(c("H", "U"
        )), .Names = ""), class = "table"), blinding_of_outcome_assessor = structure(c(H = 17L, 
        L = 8L, U = 5L), .Dim = 3L, .Dimnames = structure(list(c("H", 
        "L", "U")), .Names = ""), class = "table"), incomplete_outcome_data = structure(c(H = 10L, 
        L = 20L), .Dim = 2L, .Dimnames = structure(list(c("H", "L"
        )), .Names = ""), class = "table"))

标签: rpurrr

解决方案


使用基本 R 方式sapply

val <- c("H", "L", "U")
t(sapply(dat, function(x) {
        tot = rep(0, length(val))
        tot[match(names(x), val)] = x/sum(x)
        tot
}))

#                                  [,1]    [,2]     [,3]
#random_sequence_generation     6.66667 63.3333 30.00000
#allocation_concealment         0.00000 43.3333 56.66667
#blinding_of_participants     100.00000  0.0000  0.00000
#blinding_of_personnel         93.33333  0.0000  6.66667
#blinding_of_outcome_assessor  56.66667 26.6667 16.66667
#incomplete_outcome_data       33.33333 66.6667  0.00000

我们首先创建一个length3 的向量,match名称并通过除以x它来分配值sum。感谢@Rohit 注意到以前方法中的一个问题。


推荐阅读