在R中从频率表中创建包含单独试验的表格(table函数的反函数)

8

我有一个 R 中的 data.frame,其中列出了因子水平和成功和失败的计数的数据频率表。我想将其从频率表转换为事件列表 - 即“表格”命令的相反。具体而言,我希望将其转换为:

factor.A factor.B success.count fail.count
-------- -------- ------------- ----------
 0        1        0             2
 1        1        2             1

转化为以下内容:

factor.A factor.B result 
-------- -------- -------
 0        1        0
 0        1        0
 1        1        1
 1        1        1
 1        1        0

我认为reshape应该可以做到这一点,或者甚至是一些我没有听说过的基础函数,但我没有成功。即使是重复单个data.frame的行也很棘手——你如何将可变数量的参数传递给rbind

有什么提示吗?

背景: 为什么?因为与聚合的二项数据相比,这样的数据集更容易交叉验证逻辑拟合。

我正在使用R中的广义线性模型作为二项回归来分析我的数据,并希望进行交叉验证以控制我的数据的正则化,因为我的目的是预测。

然而,据我所知,R中的默认交叉验证例程对于二项数据并不理想,只是跳过整行频率表,而不是单独的试验。这意味着在我的代价函数中,轻度和重度采样的因子组合具有相同的权重,这对我的数据是不合适的。


2
嗯,实际上,现在我想想,这里的统计内容很少,所以这可以作为一个普通的编程问题直接发布到stackoverflow。 - dan mackinlay
没错,但请不要重复发布。我们会为您迁移此内容。 - gung - Reinstate Monica
3个回答

3
你可以尝试这个:
# create 'result' vector
# repeat 1s and 0s the number of times given in the respective 'count' column
result <- rep(rep(c(1, 0), nrow(df)), unlist(df[ , c("success.count", "fail.count")]))

# repeat each row in df the number of times given by the sum of 'count' columns
data.frame(df[rep(1:nrow(df), rowSums(df[ , c("success.count", "fail.count")]) ), c("factor.A", "factor.B")], result)

#     factor.A factor.B result
# 1          0        1      0
# 1.1        0        1      0
# 2          1        1      1
# 2.1        1        1      1
# 2.2        1        1      0

0

试试这个

  x = matrix( c(0, 1, 1, 1, 0 , 2, 2, 1), 2, 4)
  r= c()
  for(i in 1:nrow(x)) {
    r = c(r, rep(c(x[i, 1:2], 1), x[i, 3]))
    r = c(r, rep(c(x[i, 1:2], 0), x[i, 4]))
  }
  t(matrix(r, nrow= 3))

0

如果你想要一个类似tidyverse的解决方案,你可以这样做:

library(tidyverse)

df %>% gather(key = result, value = incidence, success.count, fail.count) %>% 
     mutate(result = if_else(result %>% str_detect("success"), 1, 0)) %>%
     pmap_dfr(function(factor.A, factor.B, result, incidence) 
                   { tibble(factor.A = factor.A,
                            factor.B = factor.B,
                            result = rep(result, times = incidence)
                            )
                   }
               )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接