gpt4 book ai didi

r - 如何从r中的列联表中获取带有案例的data.frame?

转载 作者:行者123 更新时间:2023-12-04 23:41:25 26 4
gpt4 key购买 nike

我想从一本书中重现一些计算(logit 回归)。书中给出了列联表和结果。

这是表:

enter image description here

    .


example <- matrix(c(21,22,6,51), nrow = 2, byrow = TRUE)
#Labels:
rownames(example) <- c("Present","Absent")
colnames(example) <- c(">= 55", "<55")

它给了我这个:
            >= 55 <55
Present 21 22
Absent 6 51

但是要使用 glm() 函数,数据必须采用以下方式:

(两列,一列是“Age”,一列是“Present”,填0/1)
    age <- c(rep(c(0),27), rep(c(1),73))
present <- c(rep(c(0),21), rep(c(1),6), rep(c(0),22), rep(c(1),51))

data <- data.frame(present, age)

> data
present age
1 0 0
2 0 0
3 0 0
. . .
. . .
. . .
100 1 1

有没有一种简单的方法可以从表/矩阵中获取此结构?

最佳答案

您也许可以使用 countsToCases功能为 defined here .

countsToCases(as.data.frame(as.table(example))) 
# Var1 Var2
#1 Present >= 55
#1.1 Present >= 55
#1.2 Present >= 55
#1.3 Present >= 55
#1.4 Present >= 55
#1.5 Present >= 55
# ...

如果您愿意,您可以随时将变量重新编码为数字。

关于r - 如何从r中的列联表中获取带有案例的data.frame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36499331/

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