【问题标题】:How do I automatically code integer variables as factors?如何自动将整数变量编码为因子?
【发布时间】:2014-07-18 16:36:33
【问题描述】:

我正在处理我想视为因素的预测变量。不幸的是,代表多项选择题答案的数据存储为整数,因此当我拟合线性模型时,R 将这些数据视为数字预测变量而不是因子。我不想每次都输入factor(x);我将如何自动将预测变量编码为因子变量?

我可能拥有的数据示例:

  a b response
1 1 T 6.946486
2 2 F 1.952378
3 3 T 5.189918
4 1 T 2.680438
5 2 F 2.243461
6 3 T 5.398814
7 1 T 2.375182
8 2 F 0.376323
9 3 T 5.144803

期望的任务:告诉 R 无需输入 lm(response ~ factor(a) + b) 预测器 a 应该被视为因子变量。也许我需要遍历每一列并保存为一个因子,然后传递给lm?也许我可以传递给lm?尝试不同的东西...

【问题讨论】:

  • data$a <- as.factor(data$a); lm(response ~ a + b, data = data) ?...这实际上是更多的输入,现在您已经更改了整个数据集。为什么要这样做?

标签: r regression lm categorical-data r-factor


【解决方案1】:

在将数据框传递给 lm 之前,将所有选择题 (MCQ) 的答案转换为因子可能是最简单的方法。假设所有整型变量都是 MSQ 答案,可以使用is.integersapply

## making up data
N <- 20
d <- data.frame(a = sample(3, N, replace=TRUE),
                b = sample(3, N, replace=TRUE),
                c = sample(3, N, replace=TRUE),
                d = sample(c(TRUE, FALSE), 10, replace=TRUE),
                e = sample(c(TRUE, FALSE), 10, replace=TRUE),
                f = sample(3, N, replace=TRUE),
                response = rnorm(20, 0, 2))

## determine which columns are integer
int_col <- which(sapply(d, is.integer))

## convert all integer variables to factor variables
d[, int_col] <- lapply(d[int_col], factor) # sapply doesn't work here
str(d)

如果您有不是 MSQ 答案的整数变量,则必须手动修改 int_col,不包括这些变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多