我最终决定将流传于互联网上的 sort.data.frame 方法放入一个 R 包中。这个方法被要求的次数太多,不能再以临时发布的方式存在。
然而,它使用的参数与通用的 sort 函数不兼容:
sort(x,decreasing,...)
sort.data.frame(form,dat)
如果我将sort.data.frame
更改为接受一个参数decreasing
,并在sort.data.frame(form, decreasing, dat)
中丢弃decreasing
,那么它就失去了简单性,因为您总是必须指定dat=
,而且不能真正使用位置参数。如果我像sort.data.frame(form,dat,decreasing)
一样将其添加到末尾,那么顺序就与通用函数不匹配。如果我希望decreasing
被包含在sort.data.frame(form,dat,...)
中,那么当使用基于位置的匹配时,我认为通用函数将把第二个位置分配给decreasing
并将其丢弃。如何协调这两个函数最好的方法是什么?完整的功能如下:
# 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
函数可能会引起一些兴趣。 - joranarrange
支持负排序:arrange(ToothGrowth,desc(dose),len)
。 - joran