2

I would like to do the following

X = matrix(0, nrow = p, ncol = N)
p=5
N=100
for (i in 1:N)
{
X[1,i] = e1(t[i])
X[2,i] = e2(t[i])
X[3,i] = e3(t[i])
X[4,i] = e4(t[i])
X[5,i] = e5(t[i])
}

where e1(). e2(), e3(), e4() and e5() are specific functions.

I have tried the following code:

for(j in 1:p)
{
for (i in 1:N)
{
    X[j,i] = as.symbol(paste("e", j, sep = ""))(t[i])
}
}

But it does not work.

Thanks for your help

Carole

Arun
  • 113,200
  • 24
  • 277
  • 373
Carolo Kanbak
  • 21
  • 1
  • 2
  • I think the question is not what you are entitling it. You are asking how to convert strings into function calls. The functions already exist and you are NOT creating names for them. – IRTFM Feb 17 '13 at 01:56

2 Answers2

2

One way to do it is to use do.call :

R> myfun <- function(x) print(x)
R> do.call(paste0("my","fun"), list("foo"))
[1] "foo"

The first argument of do.call is the name of the function (you can use paste here), and the second one is a list of arguments to pass.

juba
  • 45,570
  • 12
  • 106
  • 116
2

You want the function get

for(j in 1:p)
{
for (i in 1:N)
{
    X[j,i] = get(paste("e", j, sep = ""))(t[i])
}
}

If e1 (etc) are vectorized, you can remove one of the loops:

for (j in 1:p) {
  X[j,] = get(paste0("e", j))(t)
}
Matthew Lundberg
  • 41,139
  • 6
  • 86
  • 109