massinissa
massinissa

Reputation: 952

R: how to turn strings to arguments in order to be able to call a function?

I need to turn strings to arguments in order to be able to call a function. Here is my data:

myfunction <- function(arg1=c('val1', 'val2'), arg2=c('val1', 'val2'){
  ...
}

The user will only supply one argument (arg1 or arg2) in the form of a string. Same is for the values of this argument. For example, he may enter 'arg1' and the values as strings. The program will get those strings and have to supply them to the fonction myfunction (see bellow).

argument <- 'arg1'
values <- 'val1, val2, val3, val4, val5'

I tried:

myfunction(as.name(argument)=list(parse(text=values))) 

But it did not work.

any idea how to make it work?

Thanks

Edit

As asked by Ananda Mahto, the argument name and its values came from a web application (using shiny) as input fields. As of the function I'm using it's not mine. So I cannot modify how it accepts the arguments. But, generally speaking, it uses those arguments and values to generate a plot.

Upvotes: 0

Views: 208

Answers (1)

James
James

Reputation: 66874

Here is a way, assigning to an environment, which can be converted to a list with the correct attributes to use do.call (and getting myfunction to print its arguments):

tmp <- new.env()
assign(argument,unlist(strsplit(values,", ")),envir=tmp)
as.list(tmp)
$arg1
[1] "val1"  "val2" "val3" "val4" "val5"

do.call(myfunction,as.list(tmp))
[1] "val1" "val2" "val3" "val4" "val5"
[1] "val1" "val2"

Upvotes: 1

Related Questions