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

3

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

有什么建议吗?
1个回答

5
使用您的代码中的这一部分
#define vector
fs<-c(f,g)
names(fs)<-c("F", "G")

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

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

fs[[tag]](x)

只需稍微调整索引,以了解结构的感觉。 (例如查看fsfs[1]fs[[1]]等等)


4
一行代码中的内容为:fs <- list("F"=f, "G"=g),我的翻译是将其转化为中文并使其更加通俗易懂,但不改变原意。 - Aaron Statham
谢谢!这非常有帮助。我想我之前尝试将其取消列表化,但由于它仍然是一个列表,所以它并没有起作用,让我感到困惑。 - Ophedia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接