Melhor maneira de criar consistência genérica / método para sort.data.fram
Decidi finalmente colocar o método sort.data.frame que está flutuando pela Internet em um pacote R. Apenas é solicitado muito a ser deixado para um método de distribuição ad ho
No entanto, está escrito com argumentos que o tornam incompatível com a função de classificação genérica:
sort(x,decreasing,...)
sort.data.frame(form,dat)
Se eu mudarsort.data.frame
para diminuir como argumento, como emsort.data.frame(form,decreasing,dat)
e descartar diminuindo, então perde sua simplicidade, porque você sempre precisará especificardat=
e não pode realmente usar argumentos posicionais. Se eu adicionar no final como emsort.data.frame(form,dat,decreasing)
, o pedido não corresponde à função genérica. Se eu espero que a diminuição seja apanhada nos pontos `sort.data.frame (form, dat, ...), ao usar a correspondência baseada em posição, acredito que a função genérica atribuirá a segunda posição à diminuição e obterá descartado. Qual é a melhor maneira de harmonizar essas duas funções?
A função completa é:
# 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),]
}
Exemplo
library(datasets)
sort.data.frame(~len+dose,ToothGrowth)