【问题标题】:Recoding a factor into a binary numeric variable将因子重新编码为二进制数值变量
【发布时间】:2021-07-30 09:07:16
【问题描述】:

我有一个阳性和阴性水平的情况。 我想创建数字变量(对比编码),所以正数 = 0.5,负数 = -0.5。

我尝试了很多,但我不知道如何实现。

我很高兴得到帮助!

【问题讨论】:

标签: r recode contrast


【解决方案1】:

重新编码因子的一般方法是创建具有所需级别和标签的新因子:

recoded = factor(x, levels = c('negative', 'positive'), labels = c(-0.5, 0.5))

但现在你还有一个因素;要获取数值,您需要对其进行转换:

numeric_values = as.numeric(as.character(recoded))

请注意,首先致电as.character 很重要!如果您直接调用 as.numeric,您将使用数字级别 (1, 2),而不是因子标签。

由于上述内容有些复杂,“forcats”包提供了重新编码因子的快捷方式:

recoded = forcats::fct_recode(x, `-0.5` = 'negative', `0.5` = 'positive')

作为替代方案,您可以跳过重新编码步骤,并将您的值编码到查找向量中:

mapping = c(negative = -0.5, positive = 0.5)
numeric_values = unname(mapping[x])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2017-03-23
    • 2012-12-19
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多