小编Oph*_*dia的帖子

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

有什么建议?

r user-defined-functions

3
推荐指数
1
解决办法
143
查看次数

标签 统计

r ×1

user-defined-functions ×1