评估 R 循环中的变量 [英] Evaluating variable within R loop

查看:28
本文介绍了评估 R 循环中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 For 循环迭代生成一些函数:

I'm trying to iteratively generate some functions using a For Loop:

# Create a list to hold the functions
funcs <- list()
funcs[]

# loop through to define functions
for(i in 1:21){

    # Make function name
    funcName <- paste( 'func', i, sep = '' )

    # make function
    func = function(x){x * i}

    funcs[[funcName]] = func

    }

然而,它并没有像我希望的那样工作,因为没有在每个函数中评估 i 值.我想尝试将函数定义为等于 x * 1;x * 2;等等,但我最终得到的是一个 x * i 的函数;其中 i 是 21.

However, it's not working as I hoped as the i value is not being evaluated within each function. I want to try and define the function to equal x * 1; x * 2; etc, but what I end up with is a function that is x * i; where i is 21.

我尝试使用 eval() 函数,结果只是存储了 x * eval(i).

I tried using the eval() function and that just resulted in x * eval(i) being stored.

推荐答案

检查这个:

# Create a list to hold the functions
funcs <- list()
funcs[]

# loop through to define functions
for(i in 1:21){

    # Make function name
    funcName <- paste( 'func', i, sep = '' )

    # make function
    func = paste('function(x){x * ', i,'}',sep = '')

    funcs[[funcName]] = eval(parse(text=func))

    }

这篇关于评估 R 循环中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆