【问题标题】:R define levels without observationsR定义没有观察的水平
【发布时间】:2020-02-05 21:04:31
【问题描述】:

是否可以为向量中不存在的值定义因子水平?

我正在尝试将不包含我调查中所有可能值的整数向量 (x) 转换为具有匹配标签的因子。我希望将值 3 标记为“同意”,但由于它是 r 遇到的第一个值,因此它被分配到我的可能级别列表中的第一个级别。

> x <- c(3L,3L,3L,3L,3L)
> x <- as.factor(x)
> levels(x) <- c("Strongly disagree","Disagree", "Agree", "Strongly agree")
> summary(x)

结果:非常不同意:5,而我希望结果:同意:5

这个可以吗?

【问题讨论】:

    标签: r vector levels


    【解决方案1】:

    可以这样做,例如这样:

    x <- c(3L,3L,3L,3L,3L)
    
    factor_levels <- c("Strongly disagree","Disagree", "Agree", "Strongly agree")
    x <- factor(factor_levels[x], levels = factor_levels)
    summary(x)
    

    【讨论】:

      【解决方案2】:

      您需要指定levels 以及labels:

      x <- c(3L,3L,3L,3L,3L)
      labs <- c("Strongly disagree","Disagree", "Agree", "Strongly agree")
      factor(x, levels = seq_along(labs), labels = labs)
      #We are actually doing here 
      #factor(x, levels = 1:4, labels = labs)
      
      #[1] Agree Agree Agree Agree Agree
      #Levels: Strongly disagree Disagree Agree Strongly agree
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 2016-07-19
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2012-11-22
        • 2023-02-17
        相关资源
        最近更新 更多