【问题标题】:R is not recognizing the levels of my factor variable to allow for recoding/combiningR 没有识别我的因子变量的水平以允许重新编码/组合
【发布时间】:2021-02-22 15:41:48
【问题描述】:

我有一个数据框 (MyData1),其中因子变量分为多个级别:同意、强烈同意、不同意等。我正在尝试合并级别以使其成为二进制(例如,如果 AGREE/DISAGREE 等则为是)。

我一直在这些方面得到一些东西:

combineLevels(MyData1$V45,levs=c("Disagree"),newLabel="False")

>Error: requested levels: " Disagree " are not in the legal list of factor levels:"  Agree  Disagree  Neutral  Strongly agree 

我在重新编码功能上遇到了同样的问题。有没有办法弄清楚为什么 R 不能识别能够产生函数的级别?

【问题讨论】:

    标签: r variables recode


    【解决方案1】:

    您没有指出函数combineLevels 的来源(至少有两个版本)。在基础 R 中很容易做到:

    set.seed(42)
    V45 <- sample(c("Strongly Agree", "Agree", "Disagree", "Strongly Disagree"), 100, replace=TRUE)
    V45 <- factor(V45, levels=c("Strongly Agree", "Agree", "Disagree", "Strongly Disagree"))
    table(V45)
    # V45
    #    Strongly Agree             Agree          Disagree Strongly Disagree 
    #                28                30                16                26 
    

    只需更改级别:

    V45binary <- V45 # So we can recover the original if something goes wrong
    levels(V45binary) <- c("Yes", "Yes", "False", "False")
    table(V45binary)
    # V45binary
    #   Yes False 
    #    58    42 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      相关资源
      最近更新 更多