在 R 中,如何选择和应用函数向量的元素?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用这部分代码,
您创建了一个列表(尝试
class (fs)
或str (fs)
),因此最后一行的索引必须更改为:
只需稍微研究一下索引即可了解结构。
(例如查看
fs
、fs[1]
、fs[[1]]
等等)with this part of your code
you have created a list (try
class (fs)
orstr (fs)
)therefore the indexing of you last line has to be changed to:
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)