Question

In golfing, one tries to complete a puzzle in as few characters as possible, generally using the base language only. One trick for golfing in R is to use partial completion so that e.g. rle(...)$length can be shortened to rle(...)$l. How does one turn on function name completion in R, preferably in as few characters as possible?

Was it helpful?

Solution

`?` <- function(object){
    object <- deparse(substitute(object))
    splt <- strsplit(object,"(",fixed=TRUE)[[1]]
    object <- splt[1]
    if(length(splt)>1)
        func <- paste("(",splt[2],collapse="")
    else
        func <- ""
    envs <- sapply(search(),as.environment)
    objs <- do.call("c",lapply(envs,function(x) ls(envir=x,all.names=TRUE)))
    matches <- objs[grep(object,objs)]
    objectMatch <- matches[which.min(nchar(matches))][1]
    res <- eval(parse(text=paste(objectMatch,func,collapse="")), envir = parent.frame())
    res
}

This overloads the help operator to provide the shortest object matching the regular expression provided. For example:

> ?as.ch
function (x, ...)  .Primitive("as.character")
> a<-1
> ?as.ch(a)
[1] "1"

OTHER TIPS

Inspired by @Ian, here is a golf version of @Ian's answer. The concept is similar but use some R-ish hack (i.e., call tree manipulation)

`?`<-function(o)with(x<-as.list(substitute(o)),do.call(apropos(paste("^",deparse(x[[1]]),sep=""))[1],x[-1]))

try:

> ?me(1:5)
[1] 3
> a<-1;?as.ch(a)
[1] "1"
> 

for golf, R needs a shortcut of function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top