根据给定的顺序对数据帧进行排序 [英] Order a data frame according to a given order

查看:38
本文介绍了根据给定的顺序对数据帧进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个简单的问题。

Probably an easy question.

我有一个 data.frame (样本名称,因子水平,并复制因子级别):

I have a data.frame (names of samples, their factor level, and replicate of the factor level):

df <- data.frame(name=c("DP_A","DP_B","PA_A","PA_B","PA_C"),
                 level=c("DP","DP","PA","PA","PA"),
                 replicate=c("A","B","A","B","C"),
                 stringsAsFactors = F)

以及其列之一的给定所需顺序-因子级别:

and a given desired order of one of its columns - the factor level:

level.order <- c("PA","DP")

所以我想按 level.order 来订购 df (意思是 df $ level )。

So I'd like to order df by level.order (meaning df$level).

如果我可以再添加到 level.order ,我可以按<$ c订购$ c> df $ replicate 可以是字符(如本例所示),也可以是整数或它们的组合(例如A1,A2等)

Bonus is if I can add to secondarily to level.order I can order by df$replicate which can either be a character (as in this example), an integer, or a combination of them (e.g., A1, A2, etc)

在这种情况下, df 将是:

In this case the ordered df would be:

df <- data.frame(name=c("PA_A","PA_B","PA_C","DP_A","DP_B"),
                 level=c("PA","PA","PA","DP","DP"),
                 replicate=c("A","B","C","A","B"),
                 stringsAsFactors = F)


推荐答案

有两种选择。一种是将列与 level.order匹配 以获取数字索引,然后基于 order`

There are couple of options. One is to match the 'level' column with level.order' to get the numeric index and thenorder` based on it

df[order(match(df$level, level.order)),]

或将级别转换为因子,指定 levels 作为 level.order,然后在其上 order

Or convert the 'level' to factor specifying the levels as 'level.order' and then order on it

df[order(factor(df$level, levels = level.order)),]

这篇关于根据给定的顺序对数据帧进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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