我终于决定把在Internet上浮动的sort.data.frame方法放到R包中。它只是被请求太多而不能用于临时分配方法。为sort.data.frame创建泛型/方法一致性的最佳方法?
但是,它是写带参数,使其与通用排序功能不兼容:
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'可能会引起一些兴趣。 – joran
是的。不幸的是,它看起来不像支持负面(向后)排序,所以这个功能似乎仍然有用。 –
我很确定'arrange'确实支持负面排序:'排列(ToothGrowth,desc(dose),len)'。 – joran