R 指定因子变量

R 指定因子变量,r,R,这可能非常琐碎,但我无法理解。 我正在编写一个R脚本,它将清理/组织我的数据(仍在收集中),这样一旦数据收集完成,我就可以编写所有内容。 我遇到了一个因素变量的问题。种族/民族变量存储为数字:1=白人,2=黑人,3=亚裔,4=西班牙裔,5=其他。 目前的五个观察结果如下: race <- c(1, 1, 3, 5, 2) 我猜这是因为我说有6个标签,但在我的数据集中,6个可能结果中只有4个是观察结果。 我相信这可以用levels参数来解决,但我不知道什么时候/在哪里使用它。我试过了 ra

这可能非常琐碎,但我无法理解。 我正在编写一个R脚本,它将清理/组织我的数据(仍在收集中),这样一旦数据收集完成,我就可以编写所有内容。 我遇到了一个因素变量的问题。种族/民族变量存储为数字:1=白人,2=黑人,3=亚裔,4=西班牙裔,5=其他。 目前的五个观察结果如下:

race <- c(1, 1, 3, 5, 2)
我猜这是因为我说有6个标签,但在我的数据集中,6个可能结果中只有4个是观察结果。 我相信这可以用levels参数来解决,但我不知道什么时候/在哪里使用它。我试过了

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

race.f您得到的是
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

vec您得到的是
NA
,因为默认情况下,
race
不是
因子
,在
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

vec
race
级别为整数,创建因子时需要为所有标签定义整数:

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

race.f
race
级别为整数,创建因子时需要为所有标签定义整数:

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

race.f或者您可以将levels与labels参数一起使用,以
factor
race.f@lmo建议将帖子作为单独的答案。或者您可以将levels与labels参数一起使用,以
factor
race.f@lmo建议将帖子作为单独的答案。
race.f <- factor(race, 
                 levels = 1:6, # one for each label
                 labels = c("white", "black", "asian", 
                            "hisp", "native", "other"))