Robert Kubrick
Robert Kubrick

Reputation: 8713

Using identify and attach in a function

I want to identify data on a plot after using attach(), but I have the problem to detach before exiting my function:

f = function(x, y, data) {
  attach(data)
  plot(x, y)
  ids = identify(x, y)
  detach(data)
  return ids
}

The returned value:

<environment: 0xf785ed8>
attr(,"name")
[1] "data"
> class(i1)
[1] "environment"
> str(i1)
<environment: 0xf785ed8> 
 - attr(*, "name")= chr "data"

How can I use attach and identify in a function and return the ids of the attached object?

Upvotes: 1

Views: 58

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226182

You are trying to do non-standard evaluation here. This is always a little tricky. Can I recommend something like:

f <- function(x, y, data) {
    dx <- deparse(substitute(x))
    dy <- deparse(substitute(y))
    plot(reformulate(dx,response=dy),data)
    ids <- identify(data[,dx], data[,dy])
    return(ids)
}
f(Population,Income,state.x77)

or

f2 <- function(x, y, data) {
    x <- eval(substitute(x),envir=as.data.frame(data))
    y <- eval(substitute(y),envir=as.data.frame(data))
    plot(x,y)
    ids <- identify(x,y)
    return(ids)
}
f2(Population,Income,state.x77)

You might want to look at Hadley Wickham's notes on non-standard evaluation for more information ...

Upvotes: 2

Related Questions