Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
所以我有一个名为“Mark”的字符变量,具有 3 个级别“A”、“B”、“C”我想将其转换为数值以用于线性回归。
当我使用 as.numeric(Mark) 时,它会按字母顺序重新编码 A=1、B=2、C=3
但我想要的是按字母降序重新编码,如 A=3、B=2、C=1
我尝试将 decreasing=TRUE/FALSE, ordered=TRUE/FALSE 作为 as.numeric() 中的选项,但它似乎不起作用。有什么简单的方法可以做到这一点吗?谢谢你的帮助
您应该能够重新考虑,基于rev(levels(Mark)):
rev(levels(Mark))
set.seed(10) x <- factor(sample(LETTERS[1:5], 10, TRUE)) x # [1] C B C D A B B B D C # Levels: A B C D as.numeric(x) # [1] 3 2 3 4 1 2 2 2 4 3 as.numeric(factor(x, levels = rev(levels(x)))) # [1] 2 3 2 1 4 3 3 3 1 2