如何根据另一个类别对因子水平进行排序? [英] How to sort factor levels based on another category?

查看:52
本文介绍了如何根据另一个类别对因子水平进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含两个因素的数据框,我想对按第二个类别分组的一个因素的水平进行排序。

Say I have a data frame with two factors in there and I want to sort the levels of one factor grouped by the second category.

name <- letters[1:8]
category <- factor(sample(1:2, 8, replace=T), labels=c("A", "B"))
my.df <- data.frame(name=name, category=category)

因此数据框看起来类似于:

So the data frame looks similar to:

  name category
1    a        A
2    b        A
3    c        B
4    d        B
5    e        B
6    f        A
7    g        A
8    h        A

levels(my.df $ name)的输出是:

[1] "a" "b" "c" "d" "e" "f" "g" "h"

假定名称中的级别始终对应于数据中类别中的同一级别,如何相应地对名称级别进行排序?

Assuming that a level in name always corresponds to the same level in category in my data, how can I sort the levels of name accordingly?

推荐答案

这是什么y

> levels(my.df$name) <- as.character(unique(my.df[order(my.df$category),]$name))
> levels(my.df$name)
[1] "b" "c" "e" "f" "a" "d" "g" "h"

这篇关于如何根据另一个类别对因子水平进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆