How to call a function using the character string of the function name in R?
Those don't look like strings; that looks like a list of functions. To answer the question posed in your title, see get()
. For example, using your list but stored as character strings:
funcList <- list("*", "sin")
we can use get()
to return the function with name given by the selected element of the list:
> f <- get(funcList[[1]])
> f
function (e1, e2) .Primitive("*")
> f(3,4)
[1] 12
An alternative is the match.fun()
function, which given a string will find a function with name matching that string:
> f2 <- match.fun(funcList[[1]])
> f2(3,4)
[1] 12
but as ?match.fun
tells us, we probably shouldn't be doing that at the prompt, but from within a function.
If you do have a list of functions, then one can simply index into the list and use it as a function:
> funcList2 <- list(`*`, sin)
> str(funcList2)
List of 2
$ :function (e1, e2)
$ :function (x)
> funcList2[[1]](3, 4)
[1] 12
> funcList2[[2]](1.2)
[1] 0.9320391
or you can save the functions out as interim objects, but there is little point in doing this:
> f3 <- funcList2[[1]]
> f3(3,4)
[1] 12
> f4 <- funcList2[[2]]
> f4(1.2)
[1] 0.9320391
R evaluate character/string as the calling function name
If I understand it, you want to use a first argument as a function name? Then try to use get()
somehow:
do_something <- function(fct, arg) {
get(fct)(arg)
}
do_something("print", "Hello")
#>[1] "Hello"
do_something("mean", 1:5)
#> 3
Note that you have to be careful what you pass into. Then you can refer to argument as args[1], not args$print, if it's always the first one somehow like this:
func_enquo -> get(args[1]) # func is in place of `print`
func_enquo(value) # what matters is the print argument here.
Does that help?
R - Call a function from function name that is stored in a variable?
You could use get()
with an additional pair of ()
.
a<-function(){1+1}
var<-"a"
> get(var)()
[1] 2
How to call functions using the character string of the function name in R while using the ggplot package?
It seems ggplot2
package cannot handle data of type functions. Instead of calling the function name in main()
, you can pass the entire function body.
main <- function() {
...
...
name <- scan(what = " ")
if (name == "bar")
{ plot <- ggplot (data= df, aes(x= Dates, y= Values))
barPlot <- plot + geom_bar(stat="identity", fill="red", width=1)
print(barPlot)
}
}
This displays the graph when main()
is called on giving bar
as input.
R: Get function name called with package::function as string in R
I think substitute
could be your friend. From the docs:
substitute
returns the parse tree for the (unevaluated) expressionexpr
This allows you to access the (unevaluated) expression pack::foo
inside your function.
The following produces your desired outcome:
giveArgumentFunctionName <- function(func) {
function.name <- as.character(substitute(func))[[3]]
return (function.name)
}
giveArgumentFunctionName(pack::foo)
# [1] "foo"
giveArgumentFunctionName(pack::bar)
# [1] "bar"
Determine function name within that function
as.character(match.call()[[1]])
Demo:
my_fun <- function(){
as.character(match.call()[[1]])
}
my_fun()
# [1] "my_fun"
foo_bar <- function(){
as.character(match.call()[[1]])
}
foo_bar()
# [1] "foo_bar"
ballyhoo <- function(){
foo_bar()
}
ballyhoo()
# [1] "foo_bar"
tom_foolery <- foo_bar
tom_foolery()
# [1] "tom_foolery"
R: get the name of a function that is stored in a variable
You might be looking for substitute
:
f <- function(x) { substitute(x) }
f(mean)
Yields:
mean
which is a symbol. To get it as a string instead, add deparse
:
f <- function(x) { deparse(substitute(x)) }
f(mean)
Yields:
[1] "mean"
How to use character as variable name in arguments? [R]
We could use setNames
out <- do.call(dict, setNames(rep(list(1), length(x)), x))
out$keys
[1] "1" "2"
Or we may use invoke
or exec
library(purrr)
out <- invoke(dict, setNames(rep(1, length(x)), x))
out <- exec(dict, !!!setNames(rep(1, length(x)), x))
For the second case, also setNames
works
setNames(list(1), y)
$happy
[1] 1
or we can use dplyr::lst
dplyr::lst(!! y := 1)
$happy
[1] 1
Related Topics
Replace Na Value with the Group Value
Return a Data Frame from Function
How to Show a Legend on Dual Y-Axis Ggplot
Different Colours of Geom_Line Above and Below a Specific Value
Splitting a String into New Rows in R
How to Delete Everything After Nth Delimiter in R
Error in Plot.Window(...):Need Finite 'Xlim' Values
How to Produce Different Geom_Vline in Different Facets in R
Listing Contents of an R Data File Without Loading
Replace Na Values by Row Means
Group Integer Vector into Consecutive Runs
Sorting Each Row of a Data Frame
Processing Negative Number in "Accounting" Format
R Function Not Returning Values
How to Create Two Independent Drill Down Plot Using Highcharter
Render Dropdown for Single Column in Dt Shiny