【问题标题】:Creating a table with individual trials from a frequency table in R (inverse of table function)从 R 中的频率表(表函数的倒数)创建包含单个试验的表
【发布时间】:2014-05-14 09:55:10
【问题描述】:

我在 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 中的默认交叉验证例程不适用于二项式数据,只是跳过频率表的整行,而不是单独进行试验。这意味着轻度和重度采样的因子组合在我的成本函数中具有相同的权重,这不适合我的数据。

【问题讨论】:

  • 嗯,实际上,现在我想起来了,这里的统计内容很少,这可以作为一个正常的编程问题直接进入stackoverflow。
  • 没错,但请不要交叉发帖。我们将为您迁移它。

标签: r cross-validation frequency


【解决方案1】:

对于 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)
                            )
                   }
               )

【讨论】:

    【解决方案2】:

    试试这个

      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))
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 2016-10-31
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-13
        • 1970-01-01
        相关资源
        最近更新 更多