在R中,如何选择和应用函数向量的元素?

Oph*_*dia 3 r user-defined-functions

我有一个R问题 - 我想创建一个函数向量,然后能够按名称调用其中一个函数.但是,当我使用此名称时,我想使用映射到该名称的标记,这样我就可以在不改变代码的情况下使用我使用的名称.例如:

#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)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

mro*_*opa 5

这部分代码

#define vector
fs<-c(f,g)
names(fs)<-c("F", "G")
Run Code Online (Sandbox Code Playgroud)

你创建了一个列表(尝试class (fs)str (fs))

因此,您最后一行的索引必须更改为:

fs[[tag]](x)
Run Code Online (Sandbox Code Playgroud)

只是玩一下索引来感受结构.(例如看fs,fs[1],fs[[1]]等等)

  • 或者在一行中fs < - list("F"= f,"G"= g) (4认同)