Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional programming in R

I have been reading the Functionals from github. One suggestion in the page was to use call_function if one is working with a list of functions. Here is the code from the page:

call_fun <- function(f, ...) f(...)
f <- list(sum, mean, median, sd)
lapply(f, call_fun, x = runif(1e3))

The output was posted as:

# [[1]]
# [1] 498
# 
# [[2]]
# [1] 0.498
# 
# [[3]]
# [1] 0.49
# 
# [[4]]
# [1] 0.29

However, I was not able to replicate the above results. I got the error:

Error in FUN(X[[4L]], ...) : could not find function "f"

Am I missing something here?

like image 889
Metrics Avatar asked Aug 15 '13 16:08

Metrics


People also ask

Is R functional programming or OOP?

At its heart, R is a functional programming language. But the R system includes some support for object-oriented programming (OOP).

Is R procedural or object-oriented?

R supports procedural programming with functions and, for some functions, object-oriented programming with generic functions.

What is functional programming example?

Functional programming is based on mathematical functions. Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure, etc. Pure Functional Languages − These types of functional languages support only the functional paradigms. For example − Haskell.

What programming paradigm is R?

R is Object-Oriented In the object-oriented paradigm, you can create classes that act as blueprints for actions. An object is an instance of a class. Within a class you can have methods (functions), variables, fields, etc. R fits into this paradigm nicely. In fact, you may find that R is considered object-oriented.


1 Answers

You have redefined the function sd:

sd = 2

call_fun <- function(f, ...) f(...)
f <- list(sum, mean, median, sd)
lapply(f, call_fun, x = runif(1e3))
#Error in FUN(X[[4L]], ...) : could not find function "f"

Restart your session or do rm(sd).

like image 132
eddi Avatar answered Oct 05 '22 17:10

eddi