r - 如何从列表中生成百分比的数据框摘要
问题描述
我的数据由一个列表组成,描述了 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"))
解决方案
使用基本 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
我们首先创建一个length
3 的向量,match
名称并通过除以x
它来分配值sum
。感谢@Rohit 注意到以前方法中的一个问题。
推荐阅读
- django - django中具有基于类的功能的页面标题
- ruby - 是否可以在纯 Ruby 中指定使用特定浏览器打开 URL?
- ruby-on-rails - 安装 mini_racer (0.4.0) 时出错,Bundler 无法继续
- azure-data-explorer - 如何将当前时间戳插入/摄取到 kusto 表中
- html - 为什么有(没有)内容会影响其他内联块元素定位
- google-cloud-pubsub - 无证约束?发布到主题 *from* pubsub 触发器
- ruby-on-rails - AWS Ruby SDK 中的无效配置选项 `:dynamodb' 错误
- github - Jenkinsfile 中的条件环境变量
- python - 重新排序工作簿python中的一些工作表
- amazon-web-services - TypeError:无法读取未定义的属性“AwsCredentialsProvider”