Printing number of loop in function in R

Viewed 54

when I call in R

l <- list()
for (i in 1:4) {
  l[[i]] <- function(x) exp(i*x)
}

in each entry of the list, one can find the output

function(x) exp(i*x)

But what I want is, that I get when calling l[[1]] the output

function(x) exp(1*x)

when I call l[[2]] the output

function(x) exp(2*x)

and so on. Is there a possibility to code this in R? Thank you in advance!

3 Answers

Try

l <- sapply(1:4, function(k) eval(str2lang(sprintf("function(x) exp(%s*x)", k))))

which gives

> l
[[1]]
function (x)
exp(1 * x)
<environment: 0x000000001fb8f348>

[[2]]
function (x)
exp(2 * x)
<environment: 0x000000001fb8c350>

[[3]]
function (x)
exp(3 * x)
<environment: 0x000000001f7c4ef8>

[[4]]
function (x)
exp(4 * x)
<environment: 0x000000001f7c5c50>

Using body<- we can avoid the use of eval:

1) Use bquote on the expression assigning it to the body of the function.

l <- list()
for (i in 1:4) {
  l[[i]] <- function(x) {}
  body(l[[i]]) <- bquote(exp(.(i)*x))
}

giving this list of functions:

> l
[[1]]
function (x) 
exp(1L * x)

[[2]]
function (x) 
exp(2L * x)

[[3]]
function (x) 
exp(3L * x)

[[4]]
function (x) 
exp(4L * x)

2) This also works:

l <- list()
for (i in 1:4) {
  l[[i]] <- function(x) {}
  body(l[[i]]) <- substitute(exp(i*x), list(i = i))
}

You can use substitute:

l <- list()
for (i in 1:4) {
  l[[i]] <- substitute(function(x) exp(j*x), list(j=i))
}
l
#[[1]]
#function(x) exp(1L * x)
#
#[[2]]
#function(x) exp(2L * x)
#
#[[3]]
#function(x) exp(3L * x)
#
#[[4]]
#function(x) exp(4L * x)

In case you also want to use it for calculations you either make:

eval(l[[2]])(3)
#[1] 403.4288

or you make eval already in the loop:


l <- list()
for (i in 1:4) {
  l[[i]] <- eval(parse(text=deparse(substitute(function(x) exp(j*x), list(j=i)))))
}

l[[2]]
#function(x) exp(2L * x)

l[[2]](3)
#[1] 403.4288
Related