问题描述
我正在看手术后的移植物通畅(CABG)
在CABG手术中,单个患者通常将获得一个以上的移植物(旁路),我们正在寻找失败的时间。在原始数据中,这通过一个变量来指示,该变量指示失败的移植物数量以及诊断的时间。
我目前的原始数据是每位患者一行,我相信我需要将其移植为一行,以便继续进行KM和Cox分析。我正在考虑各种if / then循环,但想知道是否有更有效的方法在这里重新编码。
示例数据:
Patient VeinGrafts VeinsOccluded Months
1 2 0 36
2 4 1 34
3 3 2 38
4 4 0 33
为了查看此“每条静脉”,我需要重新编码,以使每个#VeinGraft都有自己的行,而VeinsOccluded变为1/0
我需要每行重复(VeinGrafts)次,这样患者2将有4行,但是其中一个具有VeinsOccluded指示器,而其他3个则没有
这就是我接下来的分析动作所需要的上述数据。
Patient VeinGrafts VeinsOccluded Months
1 2 0 36
1 2 0 36
2 4 1 34
2 4 0 34
2 4 0 34
2 4 0 34
3 3 1 38
3 3 1 38
3 3 0 38
4 4 0 33
4 4 0 33
4 4 0 33
4 4 0 33
到目前为止,这个社区非常有用,但是我找不到类似的问题答案-如果我忽略了我表示歉意,但最肯定的是您可能有任何想法!
解决方法
我们可以mutate
扩展数据,然后通过在row_number()
值上使用first
创建一个逻辑表达式,然后按“患者”,+
“静脉阻塞”分组“ VeinsOccluded”的符号,用library(dplyr)
library(tidyr)
df1 %>%
uncount(VeinGrafts,.remove = FALSE) %>%
group_by(Patient) %>%
mutate(VeinsOccluded = +(row_number() <= first(VeinsOccluded))) %>%
ungroup %>%
select(names(df1))
# A tibble: 13 x 4
# Patient VeinGrafts VeinsOccluded Months
# <int> <int> <int> <int>
# 1 1 2 0 36
# 2 1 2 0 36
# 3 2 4 1 34
# 4 2 4 0 34
# 5 2 4 0 34
# 6 2 4 0 34
# 7 3 3 1 38
# 8 3 3 1 38
# 9 3 3 0 38
#10 4 4 0 33
#11 4 4 0 33
#12 4 4 0 33
#13 4 4 0 33
-输出
data.table
或者可以通过library(data.table)
setDT(df1)[rep(seq_len(.N),VeinGrafts)][,VeinsOccluded := +(seq_len(.N) <= first(VeinsOccluded)),Patient][]
(可能以更有效的方式)完成
# Patient VeinGrafts VeinsOccluded Months
# 1: 1 2 0 36
# 2: 1 2 0 36
# 3: 2 4 1 34
# 4: 2 4 0 34
# 5: 2 4 0 34
# 6: 2 4 0 34
# 7: 3 3 1 38
# 8: 3 3 1 38
# 9: 3 3 0 38
#10: 4 4 0 33
#11: 4 4 0 33
#12: 4 4 0 33
#13: 4 4 0 33
-输出
df1 <- structure(list(Patient = 1:4,VeinGrafts = c(2L,4L,3L,4L),VeinsOccluded = c(0L,1L,2L,0L),Months = c(36L,34L,38L,33L)),class = "data.frame",row.names = c(NA,-4L))
数据
{{1}}