Reputation: 71
I wrote a command prompt in R where the user can add S4-objects.
The problem is, that I want to convert every parameter of a command that the user puts in into a character string.
For example, i have an add() command, the user can enter. The function add will add the information as a S4-object.
add("id", "name", "date", "room")
add <- function(id, name, date, room){
command <- parse(text = "keys(ID = id, OWNER = name, DATE = date, ROOM = room)")
assign(id, eval(command), envir = data)
}
input <- readline(prompt = "--> ")
eval(parse(text = input))
If the user enters something like
add(foo, "foo", "foo", "foo")
or even
add(foo, foo, foo, foo)
It will produce an error because the input will be treated as an object:
Error in add(foo, "foo", "foo", "foo") : object 'foo' not found
Any recomendations?
Upvotes: 0
Views: 255
Reputation: 173813
I agree with @Roland, that this isn't the kind of thing you want in a package for other users to employ. However, as an exercise in understanding non-standard evaluation, you could try something like the following:
First, I need to define the function keys
that needs to be evaluated in add
, since you haven't supplied this in your question. I'll make it simply return a named vector that will be stored in the data
environment
keys <- function(ID = NULL, OWNER = NULL, DATE = NULL, ROOM = NULL)
{
c(ID = ID, OWNER = OWNER, DATE = DATE, ROOM = ROOM)
}
And of course, we need an environment called data
data <- new.env()
Now, it's not clear exactly what your expected input and output is. I'll assume if the user inputs an object that doesn't exist, you just want its name stored, but if they input an object that exists, they want the value of that variable to be stored. If they input a character string, this should just be stored as is.
add <- function(id, name, date, room)
{
if(!class(substitute(id)) == "character")
if(!exists(deparse(substitute(id))))
id <- deparse(substitute(id))
if(!class(substitute(name)) == "character")
if(!exists(deparse(substitute(name))))
name <- deparse(substitute(name))
if(!class(substitute(date)) == "character")
if(!exists(deparse(substitute(date))))
date <- deparse(substitute(date))
if(!class(substitute(room)) == "character")
if(!exists(deparse(substitute(room))))
room <- deparse(substitute(room))
command <- bquote(keys(ID = .(id),
OWNER = .(name),
DATE = .(date),
ROOM = .(room)))
assign(id, eval(command), envir = data)
}
So let's create an existing variable the user might want to type in
x <- "ID_1"
So now when you call your command prompt and type
--> add(x, me, "x", room1)
You will find your variables stored in the data
environment like this:
#> data$ID_1
#> ID OWNER DATE ROOM
#> "ID_1" "me" "x" "room1"
Whereas, if x doesn't exist you get this:
data$x
#> ID OWNER DATE ROOM
#> "x" "me" "x" "room1"
Upvotes: 1