In R, how can I select and apply a feature vector element?

I have a question R - I want to create 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 that maps to this name, so that I can accidentally use the name without changing the code. For instance:

#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?

+3
source share
1 answer

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, indexing of the last row should be changed to:

fs[[tag]](x)

just play around with the indexes to get an idea of โ€‹โ€‹the structure. (e.g., see fs, fs[1], fs[[1]]etc.)

+5

Source: https://habr.com/ru/post/1761455/


All Articles