views:

65

answers:

1

I have an R question--I want to make a vector of functions, and then be able to call one of the functions by name. However, when I use this name, I want to use a tag which maps to that name, so that I can chance which name I use without having to change the code. For example:

#define tag
tag<-"F"
#define functions
f <- function(x) print(x^2)
g <- function(x) print(x^3)
#define vector
fs<-c(f,g)
names(fs)<-c("F", "G")
#create input data
x<-5
fs$F(x)
#this gives the desired output but I want to use tag
#that is, I want syntax which uses tag, so that which element I use from fs is flexible until tag is defined
#e.g. I had hoped the following would work, but it doesn't
fs[tag](x)

Any suggestions?

+5  A: 

with this part of your code

#define vector
fs<-c(f,g)
names(fs)<-c("F", "G")

you have created a list (try class (fs) or str (fs))

therefore the indexing of you last line has to be changed to:

fs[[tag]](x)

just play a bit around with the indexes to get a feeling for the structure. (eg look at fs, fs[1], fs[[1]] and so forth)

mropa
or in one line fs <- list("F"=f, "G"=g)
Aaron Statham
Thanks! This is quite helpful. I guess I had confused myself by trying to unlist it and still not having it work (since it was still a list).
Ophedia