gpt4 book ai didi

r - 从 R 中的频率表创建一个包含单独试验的表(表函数的逆)

转载 作者:行者123 更新时间:2023-12-04 08:44:11 26 4
gpt4 key购买 nike

我在 data.frame 中有一个数据频率表在 R 中列出因素级别和成功和失败的计数。我想将它从频率表转换为事件列表 - 即与“表”命令相反。具体来说,我想把这个:

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

最佳答案

你可以试试这个:

# 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

关于r - 从 R 中的频率表创建一个包含单独试验的表(表函数的逆),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22822922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com