问题
So, I Have the following very simple map.r file.
I'm trying to have the user type "click" in interactive mode and then have the function .
Since it's a function, the user has to type "click()" how can I make it so that they only have to the word (w/o parentheses), and then have that function do something with the img.
So the user types:
mydist("image.pnm")
click
//And then the function click does what it's supposed to
mydist <- function(mapfile) {
img <- read.pnm(mapfile)
plot(img)
}
click <- function() {
//Prompt user to click on img
}
回答1:
If you give it a class of its own and a print method which echoes that message you can achieve your goal.
print.click <- function(x, ...){
#
# could do something here
# the <something> could be a plot or calculation
plot(1:10, 10:1, type="l")
cat("Your click message here\n perhaps \n Downward line plotted!")
invisible(x)
}
click <- "click"
class(click) <- "click"
click
# Your click message here
# perhaps
# Downward line plotted!
Even if you wanted to "encapsulate" the class definition in the object itself as Aaron demonstrated, you would not be limited to printing a message. You could do something like this:
print.click <- function(x, ...) {plot(1:10, 10:1, type="l")
cat("prompt user to click on img...\n")
If you wanted to call locator
, you could extend the interactivity with the user.
回答2:
Here's the 'proper' way to do it. This is an example from my .Rprofile file.
invisible(makeActiveBinding("newq", function(...){quartz();par(cex=.75); cat("OK\n")}, .GlobalEnv))
The function makeActiveBinding
does some sort of magic so the complete function gets called w/o need for any parentheses.
回答3:
Here's one way to do what you've asked for. However, there may be a better way to do what you're trying to do.
click <- structure(1, class="click")
print.click <- function(x, ...) {
cat("prompt user to click on img...\n")
}
Then
> click
prompt user to click on img...
回答4:
I could be totally confused as to what you want to do, but I think something like below may answer your query. It can be expanded upon by adding other 'else-if' options and other custom functions to be run as a result of whatever the user types.
customfunction <- function() {
print(1:10)
}
mydist <- function(mapfile) {
img <- read.pnm(mapfile)
plot(img)
ANSWER <- readline("")
# customfunction() will be run (printing 1:10) as soon as
# the user types "click" and hits enter
if (ANSWER=="click") customfunction()
}
来源:https://stackoverflow.com/questions/8130469/r-programming-function-without