重新排序因子级别并将新订单应用于原始数据

时间:2016-01-26 04:19:23

标签: r

目前我有3列的df数据。

sizes <- factor(c("small", "large", "large", "small", "medium"))
c <- sample(1:5)
a <- c("M","M","F","M","F")
df <- data.frame(sizes,c,a)
> head(df$sizes)
[1] small  large  large  small  medium
Levels: large medium small

> head(df)
       sizes c a
    1  small 1 M
    2  large 3 M
    3  large 4 F
    4  small 5 M
    5 medium 2 F

我正在尝试将因子数据大小重新排序为“小”,“中”,“大”并将其应用回df。

申请后

sizes <- factor(sizes, levels = c("small", "medium", "large"))
sizes
[1] small  large  large  small  medium
Levels: small medium large

但我的原始数据集仍未重新排序

> head(df$sizes)
[1] small  large  large  small  medium
Levels: large medium small

有人帮忙吗?

1 个答案:

答案 0 :(得分:1)

我们指定levels中的factor重新排序。

 df$sizes <- factor(df$sizes, levels = c("small", "medium", "large"))