【问题标题】:Automatic creation and use of custom made function in R在 R 中自动创建和使用自定义函数
【发布时间】:2019-02-02 13:48:10
【问题描述】:

我想在 for 循环中创建评估不同的索引。 这些指数有不同的公式,并不总是需要评估。 f.i. : 我要评估的指标可能是

a=1
b=2
c=5
d=8
IDX1=function(a,b) {result=a+b}
IDX2=function(c,b) {result=c+b}
IDX3=function(d,b) {result=d+b-c}
IDX4=function(a,d) {result=a+d+b+c}

公式并不重要

在数据框中,我有迭代次数和每次循环需要采用的索引(假设我必须为每次迭代评估 2 个索引)

head=c("iter","IndexA","IndexB")
r1=c(1,"IDX1","IDX2")
r2=c(2,"IDX3","IDX4")
r3=c(3,"IDX1","IDX4")
df=as.data.frame(rbind(head,r1,r2,r3))

我想做的是在循环中为每次迭代评估各自的 2 个索引,自动调用正确的公式广告并使用正确的参数提供给它

iter 1 : IndexA=IDX1(args)=3  ; IndexB(args)=IDX2(args)=7
iter 2 : IndexA=IDX3(args)=5  ; IndexB(args)=IDX4(args)=16
iter 3 : IndexA=IDX1(args)=3  ; IndexB(args)=IDX4(args)=16

请不要回答“只需运行所有功能并调用 循环中需要的结果”。

我正在使用大矩阵,内存确实是个问题。我需要评估循环内的函数以减少内存的使用

我相信答案是这个讨论中的一些内容,但我无法理解。

How to create an R function programmatically?

谁能解释一下 1.如何构建一个可以在循环中以编程方式改变的函数? 2. 一旦我有了它,我怎样才能运行公式并得到我想要的结果? 谢谢

【问题讨论】:

    标签: r function loops


    【解决方案1】:

    您可以结合使用eval 和parse 函数来调用(评估)任何字符串作为代码。首先,你必须构造这样一个字符串。为此,您可以将索引指定为字符串。例如:IDX1 = "a + b"。然后,您可以使用 get("IDX1") 按名称获取该值。

    试试这个代码:

    # Your preparations
    a <- 1
    b <- 2
    c <- 5
    d <- 8
    IDX1 <- "a + b"
    IDX2 <- "c + b"
    IDX3 <- "d + b - c"
    IDX4 <- "a + d + b + c"
    
    
    head = c("iter", "IndexA", "IndexB")
    r1 = c(1, "IDX1", "IDX2")
    r2 = c(2, "IDX3", "IDX4")
    r3 = c(3, "IDX1", "IDX4")
    df = as.data.frame(rbind(r1, r2, r3))
    colnames(df) <- head
    
    # Loop over df with apply
    result <- apply(df, 1, function(x){
        # Construct call string for further evaluation
        IndexA_call <- paste("ia <- ", get(x[2]), sep = "")
        IndexB_call <- paste("ib <- ", get(x[3]), sep = "")
    
        # eval each call string
        eval(parse(text = IndexA_call))
        eval(parse(text = IndexB_call))
    
        x[2:3] <- c(ia, ib)
        return(as.numeric(x))
    })
    
    result <- t(result)
    colnames(result) <- head
    print(result)
    

    这给出了:

       iter IndexA IndexB
    r1    1      3      7
    r2    2      5     16
    r3    3      3     16
    

    【讨论】:

    • 我尝试了代码广告,它完美地完成了工作。谢谢
    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多