评估R循环内的变量 [英] Evaluating variable within R loop
本文介绍了评估R循环内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#创建一个列表来保存函数
funcs< - list()
funcs []
#循环定义函数
for(i in 1:21){
$ make函数名称
funcName< - paste('func',i,sep ='')
#make函数
func = function(x){x * i}
funcs [[funcName]] = func
}
然而,它不工作,因为我不希望在每个函数中评估i值。我想尝试定义函数等于x * 1; x * 2;等等,但我最终是一个函数是x *我;我试图使用eval()函数,只是导致存储x * eval(i)。
#创建一个列表到解决方案
持有函数
funcs< - list()
funcs []
#循环定义函数
for(i in 1:21){
$ b $ make函数名$ b $ funcName< - paste('func',i,sep ='')
$ b $ make#$ b $ func = paste 'function(x){x *',i,'}',sep ='')
funcs [[funcName]] = eval(parse(text = func))
}
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
}
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.
I tried using the eval() function and that just resulted in x * eval(i) being stored.
解决方案
Check this one:
# 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屋!
查看全文