对R中非平凡元素的列表进行排序 [英] Sort a list of nontrivial elements in R

查看:161
本文介绍了对R中非平凡元素的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我有一个非平凡对象的列表(它们不是像标量那样的简单对象,可以期望R能够为其定义阶数).我想对列表进行排序.大多数语言都允许程序员提供一个函数或类似函数,用于比较传递给排序函数的一对列表元素.如何对列表进行排序?

In R, I have a list of nontrivial objects (they aren't simple objects like scalars that R can be expected to be able to define an order for). I want to sort the list. Most languages allow the programmer to provide a function or similar that compares a pair of list elements that is passed to a sort function. How can I sort my list?

推荐答案

我可以简单地说,您的对象是具有两个元素(名称和值)的列表.该值为数字;这就是我们要排序的依据.您可以想象有更多的元素并且需要做一些更复杂的排序.

To make this is as simple I can, say your objects are lists with two elements, a name and a value. The value is a numeric; that's what we want to sort by. You can imagine having more elements and needing to do something more complex to sort.

sort帮助页面告诉我们sort使用xtfrmxtfrm依次告诉我们它将对x[i]类使用==>方法.

The sort help page tells us that sort uses xtfrm; xtfrm in turn tells us it will use == and > methods for the class of x[i].

首先,我将定义一个要排序的对象:

First I'll define an object that I want to sort:

xx <- lapply(c(3,5,7,2,4), function(i) list(name=LETTERS[i], value=i))
class(xx) <- "myobj"

现在,由于xtfrm适用于x[i],因此我需要定义一个[函数,该函数返回所需的元素,但仍具有正确的类

Now, since xtfrm works on the x[i]'s, I need to define a [ function that returns the desired elements but still with the right class

`[.myobj` <- function(x, i) {
  class(x) <- "list"
  structure(x[i], class="myobj")
}

现在,对于myobj类,我们需要==>函数;适当地矢量化处理,可能会变得更聪明;但是对于sort函数,我们知道我们只会传递长度为1的myobj,因此我将仅使用第一个元素来定义关系.

Now we need == and > functions for the myobj class; this potentially could be smarter by vectorizing these properly; but for the sort function, we know that we're only going to be passing in myobj's of length 1, so I'll just use the first element to define the relations.

`>.myobj` <- function(e1, e2) {
  e1[[1]]$value > e2[[1]]$value
}

`==.myobj` <- function(e1, e2) {
  e1[[1]]$value == e2[[1]]$value
}

现在sort可以正常工作.

sort(xx)

为对象编写完整的Ops函数可能更合适;但是,仅此而已,这似乎就是您所需要的.有关使用S3样式执行此操作的更多详细信息,请参见Venables/Ripley中的第89-90页.另外,如果您可以轻松地为对象编写xtfrm函数,那会更简单,而且很有可能会更快.

It might be considered more proper to write a full Ops function for your object; however, to just sort, this seems to be all you need. See p.89-90 in Venables/Ripley for more details about doing this using the S3 style. Also, if you can easily write an xtfrm function for your objects, that would be simpler and most likely faster.

这篇关于对R中非平凡元素的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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