我有一个数据集如下:
patient_id pre.int.outcome post.int.outcome
302949 1 1
993564 0 1
993570 1 1
993575 0 1
993792 1 0
我想为每位患者进行clogit前/后干预
我知道我需要将其纳入表格:
strata outcome
1 1
1 1
2 0
2 0
3 0
3 1
在这种形式中,阶层是患者数量对和结果,但我不知道该怎么做。任何人都可以帮助或指导有助于此的来源吗?
编辑:我最终做的是使用重塑功能使数据集“长”。而不是广泛;
ds1<-reshape(ds, varying=c('pre.int.outcome','post.int.outcome'), v.names='outcome', timevar='before_after', times=c(0,1), direction='long')
我按Patient_id排序,将其用作我的分层&#39;。
ds1[order(ds1$patient_id),]
答案 0 :(得分:4)
可能有帮助
data.frame(strata= rep(1:nrow(df1), each=2), outcome=c(t(df1[2:3])))
答案 1 :(得分:2)
基于akrun的评论和回答,这是使用reshape2
包melt
的解决方案:
library(reshape2)
# I created dummy data to make sure my answer works
# I assumed 4 intervention treatments, but this would work with
# two treatments. With the dummy data, just make sure nObs/4 is an integer
nObs = 100 # number of observations
d = data.frame(patient_id = 1:4,
pre.int.outcome = rbinom(4, 1, 0.7),
post.int.outcome = rbinom(4, 1, 0.5),
intervention = rep(c("a", "b", "c", "d"), each = nObs/4))
# melting the data as suggested by akrun
d2 = melt(d, id.vars = c("patient_id", "intervention"))
# Creating a strata variable for you with paste
d2$strata = as.factor(paste(d2$patient_id, d2$variable))
# I also clean up the variable to remove patient_id
# useful if you are concerned about protecting pii
levels(d2$strata) = 1:length(d2$strata)
# last, I clean up the data and create a third "pretty" data.frame
d3 = d2[ , c("intervention", "value", "strata")]
head(d3)
# intervention value strata
# 1 a 1 2
# 2 a 1 4
# 3 a 1 6
# 4 a 1 8
# 5 a 1 2
# 6 a 1 4
# I also throw in the logistic regression
myGLM = glm(value ~ intervention, data = d3, family = 'binomial')
summary(myGLM)
# prints lots of outputs to screen ...
# or if you need odds ratios
myGLM2 = glm(value ~ intervention - 1, data = d3, family = 'binomial')
exp(myGLM2$coef)
exp(confint(myGLM2))
# also prints lots of outputs to screen ...
编辑:我根据OP的评论添加了intervention
。我还添加了glm
以进一步帮助她或他。