R Eval issue with function return

时间:2017-04-13 14:52:28

标签: r function eval

Can anyone tell me why the use of eval(parse(text=xxxx)) fails when it is used to select between one of several data frames to output as the return from a function

e.g. I have three data frames generated within a function;

aaa.df, bbb.df, ccc.df

and a 'mode' parameter e.g. aaa / bbb / ccc (which denotes in this case which data frame to return from the function)

the following two-liner works fine

eval(parse(text=paste("output.df<-",mode,".df", sep="")))
return(output.df)

however when I try to condense these two lines purely for a little added brevity, removing the intermediate assignment to output.df, it doesn't output the data frame

e.g.

eval(parse(text=paste("return(",mode,".df)", sep="")))

It will not be a big deal for me to continue with the first approach until I end up with a very large data frame to return, at which point I assume there could be some performance / memory hit.

1 个答案:

答案 0 :(得分:2)

只需删除return,这完全没必要,老实说根本没有意义。

eval(parse(text=paste0(mode,".df")))

更好的是,不要在这里使用eval - 它可能是最糟糕的解决方案。而是将您的数据放入结构化表或列表格式。或者,最糟糕的情况是,使用get

get(paste0(mode, '.df'))

但实际上,只需将数据放入命名列表中即可。