将chr转换为有序因子并设置因子水平导致错误

时间:2017-02-24 04:30:46

标签: r

我有一个dataframe作为R,如下所示,其中包括条件"使用","认证二手"和"新。在我的实际数据集中,当我读入数据集时,此变量将作为chr加载。使用factor函数,我知道如何将chr转换为factor,但我想保持因子的顺序,并设置"使用"作为基线。

我尝试过所有可以找到的东西,但我显然遗漏了一些东西。如何正确将chr转换为有序因子并指定订单级别?

# example df
df <- data.frame(condition = c('Certified pre-owned', 'Used', 'Used', 'Used', 'Used', 'Used', 'New', 'Used', 'Used'))

# show structure
str(df)

'data.frame':   9 obs. of  1 variable:
 $ condition: Factor w/ 3 levels "Certified pre-owned",..: 1 3 3 3 3 3 2 3 3

# change order of conditoin
df$condition <- as.ordered(df$condition, levels=c("Used", "Certified pre-owned", "New"))

Error in as.ordered(df$condition, levels = c("Used", "Certified pre-owned", : unused argument (levels = c("Used", "Certified pre-owned", "New"))
Traceback:

1. as.ordered(df$condition, levels = c("Used", "Certified pre-owned", "New"))

# convert to factor, but without levels
df$condition <- as.ordered(factor(df$condition))

# but the order puts them in alphabetical order, which is not what I want
levels(df$condition)

'Certified pre-owned' 'New' 'Used' 

0 个答案:

没有答案