【问题标题】:Specifying factor variables指定因子变量
【发布时间】:2017-02-07 20:06:20
【问题描述】:

这可能是非常微不足道的,但我无法弄清楚。 我正在编写一个 R 脚本,它将清理/组织我的数据(仍在收集),这样一旦数据收集完成,我就会把所有东西都写好。 我遇到了因子变量的问题。种族/民族变量存储为数字:1 = 白人,2 = 黑人,3 = 亚洲人,4 = 西班牙裔,5 = 其他。 现在,五个观察结果如下所示:

race <- c(1, 1, 3, 5, 2)

我想将比赛变量转换为因子,所以我尝试了:

race.f <- factor(race, labels = c("white", "black", "asian", "hisp",
"native", "other"))

但我得到了错误:

Error in factor(race, labels = c("white", "black", "asian", "hisp", 
"native",  : invalid 'labels'; length 6 should be 1 or 4

我猜这是因为我说有 6 个标签,但在我的数据集中只有 6 个可能结果中的 4 个的观察结果。 我确信这可以通过 levels 参数解决,但我不知道何时/何地使用它。我试过了

race.f <- factor(race, levels = c("white", "black", "asian", "hisp", 
"native", "other")) 

它只是创建了一堆 NA。 如果我碰巧从 6 个种族中的每个种族中至少收集一个人的数据,我上面发布的代码就可以工作。但是,不能保证会发生这种情况。在收集数据之前编写脚本时,我应该如何处理这个问题?我希望它能够处理所有可能的结果。 谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    racelevels 是整数,需要在创建因子时为所有标签定义:

    race.f <- factor(race, 
                     levels = 1:6, # one for each label
                     labels = c("white", "black", "asian", 
                                "hisp", "native", "other"))
    

    【讨论】:

      【解决方案2】:

      您得到NA,因为默认情况下race 不是factor,并且在factor() 中使用它会导致NA,因为它无法在race 中找到指定的级别。因此我们必须首先将race中的值匹配到它们对应的races

      为此,我们需要如下所示的查找向量:

      vec <- c("white"=1, "black" = 2, "asian" = 3,"hispanic" = 4, "other" = 5)
      
      set.seed(100)
      race <- sample(1:5, 8, replace = T)
      # [1] 2 2 3 1 3 3 5 2
      
      race_new <- names(vec)[match(race, vec)] # match() returns the position where race matched with vec in vec
      factor(race_new, levels = names(vec))
      # [1] black black asian white asian asian other black
      # Levels: white black asian hispanic other
      

      @Imo 的建议(更简洁):或者您可以将级别与标签参数一起用于因子:

      race.f <- factor(race, levels=1:6, labels = c("white", "black", "asian",
                                                    "hisp", "native", "other"))
      

      【讨论】:

      • 或者您可以将级别与factor 的标签参数一起使用:race.f &lt;- factor(race, levels=1:6, labels = c("white", "black", "asian", "hisp", "native", "other"))
      • @lmo 建议作为单独的答案发布。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      相关资源
      最近更新 更多