我有以下数据框:
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")
变量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]
我想将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
最有效的方法是什么? 非常感谢您提前
答案 0 :(得分:6)
这是一种方法:
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
这里的基本想法是head
和tail
都有一个“n
”参数,可让您从“头部”和“尾部”指定所需的值。你的矢量或数据集。这样,我们就可以轻松抓取向量A的(96.4,100]
和(100, Inf]
以及向量B的相关值。
within
是动态替换data.frame
中的值的便捷方式。
答案 1 :(得分:3)
如您所知,这些因素是有序的,您可以执行以下操作
within(forStack, {
Ar <- (as.integer(A) < length(levels(A))-1)*1
Br <- (as.integer(B) > 2)*1
})