R-超过2个序数变量中的分类因子



我在比较3个以上的序数变量中有一个问题。

我已经在rstudio和Datacamp上尝试过。在处理2个以上的序数变量(低,中,高(的特定顺序之后,当比较高和中等时,为什么"高>媒体"会产生false?

temperature_vector <- c("High", "Low", "High","Low", "Medium")
factor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c("Low", "Medium", "High"))
factor_temperature_vector 
#The above line returns:
#[1] High   Low    High   Low    Medium
#Levels: Low < Medium < High
high <- temperature_vector[1]
medium <- temperature_vector[5]
low <- temperature_vector[2]
high > low #returns FALSE
high > medium #returns FALSE. Why?

解决:

需要比较因素而不是变量:

high <- **factor_**temperature_vector[1]
medium <- **factor_**temperature_vector[5]
low <- **factor_**temperature_vector[2]

标识符的分配来自character向量,而不是factor向量。对于character字符串,订购是字母顺序,其中h小于m

high <- factor_temperature_vector[1]
medium <- factor_temperature_vector[5]
low <- factor_temperature_vector[2]
high > low
#[1] TRUE
high > medium
#[1] TRUE

最新更新