免责声明:我不确定“崩溃”是否适合此操作。如果有更合适的术语,我会全力以赴。
我有数百名患者随着时间的推移多次观察的症状严重程度数据。严重性是按顺序定义的。这是一个简化的示例:
# Create example dataset
example.dat <- data.frame(
ID = c(1,1,1,2,2,2,3,3,3,4,4,4), # patient ID numbers
Time = c("T1", "T2", "T3", "T1", "T2", "T3", # times at which data were collected
"T1", "T2", "T3", "T1", "T2", "T3"),
Severity = c("Mild", "Moderate", "Mild", # severity of symptoms
"Severe", "Severe", "Moderate",
"None", NA, "None",
"Moderate", "Moderate", "Mild")
)
# Specify the order of the factor levels
example.dat$Severity <- ordered(example.dat$Severity,
levels = c("None",
"Mild",
"Moderate",
"Severe")
)
example.dat
生成的数据框如下所示:
ID Time Severity
1 1 T1 Mild
2 1 T2 Moderate
3 1 T3 Mild
4 2 T1 Severe
5 2 T2 Severe
6 2 T3 Moderate
7 3 T1 None
8 3 T2 <NA>
9 3 T3 None
10 4 T1 Moderate
11 4 T2 Moderate
12 4 T3 Mild
我想创建一个新列,其中包含为每个 ID 观察到的最严重症状(即有序因子的最高级别),如下所示:
ID Time Severity Worst
1 1 T1 Mild Moderate
2 1 T2 Moderate Moderate
3 1 T3 Mild Moderate
4 2 T1 Severe Severe
5 2 T2 Severe Severe
6 2 T3 Moderate Severe
7 3 T1 None None
8 3 T2 <NA> None
9 3 T3 None None
10 4 T1 Moderate Moderate
11 4 T2 Moderate Moderate
12 4 T3 Mild Moderate
从那里,我可以轻松地创建这个数据框的子集,其中包括,对于每个 ID,最近观察的时间和研究期间报告的最严重症状:
ID Time Worst
3 1 T3 Moderate
6 2 T3 Severe
9 3 T3 None
12 4 T3 Moderate
有什么想法吗?