【发布时间】:2011-10-13 19:08:39
【问题描述】:
我最终决定将互联网上流传的 sort.data.frame 方法放入 R 包中。它只是被要求太多,不能留给一种特殊的分发方法。
但是,它使用的参数使其与通用排序函数不兼容:
sort(x,decreasing,...)
sort.data.frame(form,dat)
如果我将 sort.data.frame 更改为像 sort.data.frame(form,decreasing,dat) 中那样将递减作为参数并丢弃递减,那么它就会失去其简单性,因为您总是必须指定 dat= 并且不能真正使用位置参数。如果我像sort.data.frame(form,dat,decreasing) 一样将其添加到末尾,则该顺序与通用函数不匹配。如果我希望递减在点`sort.data.frame(form,dat,...)中被捕获,那么当使用基于位置的匹配时,我相信通用函数会将第二个位置分配给递减并且它会得到丢弃。协调这两个功能的最佳方法是什么?
完整的功能是:
# Sort a data frame
sort.data.frame <- function(form,dat){
# Author: Kevin Wright
# http://tolstoy.newcastle.edu.au/R/help/04/09/4300.html
# Some ideas from Andy Liaw
# http://tolstoy.newcastle.edu.au/R/help/04/07/1076.html
# Use + for ascending, - for decending.
# Sorting is left to right in the formula
# Useage is either of the following:
# sort.data.frame(~Block-Variety,Oats)
# sort.data.frame(Oats,~-Variety+Block)
# If dat is the formula, then switch form and dat
if(inherits(dat,"formula")){
f=dat
dat=form
form=f
}
if(form[[1]] != "~") {
stop("Formula must be one-sided.")
}
# Make the formula into character and remove spaces
formc <- as.character(form[2])
formc <- gsub(" ","",formc)
# If the first character is not + or -, add +
if(!is.element(substring(formc,1,1),c("+","-"))) {
formc <- paste("+",formc,sep="")
}
# Extract the variables from the formula
vars <- unlist(strsplit(formc, "[\\+\\-]"))
vars <- vars[vars!=""] # Remove spurious "" terms
# Build a list of arguments to pass to "order" function
calllist <- list()
pos=1 # Position of + or -
for(i in 1:length(vars)){
varsign <- substring(formc,pos,pos)
pos <- pos+1+nchar(vars[i])
if(is.factor(dat[,vars[i]])){
if(varsign=="-")
calllist[[i]] <- -rank(dat[,vars[i]])
else
calllist[[i]] <- rank(dat[,vars[i]])
}
else {
if(varsign=="-")
calllist[[i]] <- -dat[,vars[i]]
else
calllist[[i]] <- dat[,vars[i]]
}
}
dat[do.call("order",calllist),]
}
例子:
library(datasets)
sort.data.frame(~len+dose,ToothGrowth)
【问题讨论】:
-
plyr包中的函数arrange可能有点意思。 -
是的。不幸的是,它看起来不支持负(向后)排序,所以这个函数看起来仍然很有用。
-
我很确定
arrange确实支持负排序:arrange(ToothGrowth,desc(dose),len)。 -
用 plyr 写了一个完整的答案——感谢@joran 的例子!