繁体   English   中英

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

[英]In R, how can an element of a vector of functions be selected and applied?

我有一个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)

有什么建议?

这部分代码

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

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

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

fs[[tag]](x)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM