我有以下数据框:
forStack
AGE BMI time A B ID
1 59 23.8 0 (0,75] (4,14.9] 9000099
2 69 29.8 0 (96.4,100] (-Inf,0] 9000296
3 71 22.7 0 (75,89.3] (4,14.9] 9000622
4 56 32.4 0 (0,75] (14.9,68] 9000798
5 72 30.7 0 (0,75] (14.9,68] 9001104
6 75 23.5 0 (96.4,100] (0,4] 9001400
dput (forStack)
structure(list(AGE = c(59, 69, 71, 56, 72, 75), BMI = c(23.8,
29.8, 22.7, 32.4, 30.7, 23.5), time = c(0, 0, 0, 0, 0, 0), A = structure(c(2L,
5L, 3L, 2L, 2L, 5L), .Label = c("(-Inf,0]", "(0,75]", "(75,89.3]",
"(89.3,96.4]", "(96.4,100]", "(100, Inf]"), class = "factor"),
B = structure(c(3L, 1L, 3L, 4L, 4L, 2L), .Label = c("(-Inf,0]",
"(0,4]", "(4,14.9]", "(14.9,68]", "(68, Inf]"), class = "factor"),
ID = c(9000099, 9000296, 9000622, 9000798, 9001104, 9001400
)), .Names = c("AGE", "BMI", "time", "A", "B", "ID"), row.names = c(NA,
6L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)
变量A和B是代表四分因素:
forStack$A
[1] (0,75] (96.4,100] (75,89.3] (0,75] (0,75] (96.4,100]
Levels: (-Inf,0] (0,75] (75,89.3] (89.3,96.4] (96.4,100] (100, Inf]
forStack$B
[1] (4,14.9] (-Inf,0] (4,14.9] (14.9,68] (14.9,68] (0,4]
Levels: (-Inf,0] (0,4] (4,14.9] (14.9,68] (68, Inf]
Run Code Online (Sandbox Code Playgroud)
我想重新编码A并将B值归结为两级因子,如下所示:
为A,上部因子水平(96.4,100]和(100, Inf]应该被重新编码为0电平,其他级别-级别1
对于B最低因子水平(-Inf,0] ,(0,4]应记录为0水平,其他水平 - 为1水平
因此,数据框应如下所示:
forStack
AGE BMI time A B ID
1 59 23.8 0 1 1 9000099
2 69 29.8 0 0 0 9000296
3 71 22.7 0 1 1 9000622
4 56 32.4 0 1 1 9000798
5 72 30.7 0 1 1 9001104
6 75 23.5 0 0 0 9001400
Run Code Online (Sandbox Code Playgroud)
最有效的方法是什么?非常感谢你提前
这是一种方法:
within(forStack, {
A <- as.numeric(!A %in% tail(levels(A), 2))
B <- as.numeric(!B %in% head(levels(B), 2))
})
# AGE BMI time A B ID
# 1 59 23.8 0 1 1 9000099
# 2 69 29.8 0 0 0 9000296
# 3 71 22.7 0 1 1 9000622
# 4 56 32.4 0 1 1 9000798
# 5 72 30.7 0 1 1 9001104
# 6 75 23.5 0 0 0 9001400
Run Code Online (Sandbox Code Playgroud)
这里的基本想法是,head和tail都有一个" n"的说法,让你指定你从想要多少价值的"头"和"你的载体或数据集的尾巴".这让我们很容易地抓住(96.4,100]和(100, Inf]矢量A和矢量B的相关值
within是一种动态替换你的值的便捷方式data.frame.