【问题标题】:Using frequency data to populate dataframe in R使用频率数据填充 R 中的数据框
【发布时间】:2015-10-17 03:30:07
【问题描述】:

我正在尝试对现有的元分析进行建模以检查替代假设(例如,进行随机效应分析)以及重新采样技术。有超过 2,000 名受试者,但数据相当简单:二元结果,成功或失败,与结构化评估的分数 (0-10) 相关联。我有每个分数的成功或失败频率,嵌套在每个研究中。我正在寻找一种更简单的方法来创建数据集,而不是键入它,或者多次使用 rep 函数。

我希望每一行看起来像这样: Study_ID、Test_Result[0-10]、Outcome[0 或 1]

例如,假设我只有两个研究和两个测试级别(1 或 2):研究 1 有 35 次成功,85 次失败,得分为“1”;得分为“2”,46 次成功,83 次失败。在研究 2 中,得分为“1”的有 78 次成功,246 次失败;得分为“2”,成功 45 次,失败 96 次。

仅使用提供的频率,我怎样才能最轻松地创建包含数百行数据的数据框?

【问题讨论】:

  • 欢迎来到 SO,请提供 dput(head(your_data, 10)) 以便我们查看您的数据是什么样的以及(如果可能)所需的输出。

标签: r resampling


【解决方案1】:

这可能有效,唯一需要修改以添加更多研究的是studies 列表。

## Your specifications
## Put the lengths of each grouping/study in a list so it's easy to work with
studies <- list(
    study1 = c(35, 85, 46, 83),
    study2 = c(78, 246, 45, 96))
score <- rep(1:2, each=2) # 1 1 2 2
type <- rep(0:1, len=4)   # 0 1 0 1

## Repeat score/type by counts of each grouping/study
res <- lapply(studies, function(study)
    data.frame(
        score=rep(score, study),
        type=rep(type, study)
    ))

## Combine into data.frame
dat <- data.frame(study=rep(seq_along(studies), times=sapply(studies, sum)),
                  as.list(do.call(rbind, res)))
head(dat)
#   study score type
# 1     1     1    0
# 2     1     1    0
# 3     1     1    0
# 4     1     1    0
# 5     1     1    0
# 6     1     1    0

## Check counts
with(dat, table(type, score, study))
# , , study = 1
# 
#     score
# type   1   2
#    0  35  46
#    1  85  83
# 
# , , study = 2
# 
#     score
# type   1   2
#    0  78  45
#    1 246  96

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2016-09-07
    • 2021-11-19
    相关资源
    最近更新 更多