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

发布于 2024-09-15 12:53:43 字数 569 浏览 6 评论 0原文

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

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

oО清风挽发oО 2024-09-22 12:53:43

使用这部分代码,

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

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

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

fs[[tag]](x)

只需稍微研究一下索引即可了解结构。
(例如查看fsfs[1]fs[[1]]等等)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文