例如,我有一个向量:
df <- c(NA, "Travellers' Choice, Certificate of Excellence 2020, Certificate of Excellence 2017", "Certificate of Excellence 2017","Certificate of Excellence 2018, Certificate of Excellence 2017, Certificate of Excellence 2016")
我想做这样的事情:
df.ordered <- as.numeric(factor(df, levels=length(df), ordered=TRUE))
要将其作为输出:
[1] NA 10 4 12
Levels: 4 < 10 < 12
您只需要使级别成为向量中的唯一值:
as.numeric(factor(df, levels=sort(unique(df)), ordered=TRUE))
[1] 3 2 3 1