Why is it a bad habit to parse and evaluate a string code (in R)? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 17:48:51

问题


I've been told that it is a bad habit to parse and evaluate a character string

to_run = "for (i in 1:10){print(i);print('Hello World!')}"

eval(parse(text=to_run))

Why is it a bad habit?

It seems to me to be quite a flexible way of programming as we can construct our code in a iterative manner by pasting character strings together. For example it allows to easily deal with objects of various dimensions for example.

if (length(dim(my.array)) == 2){to_run = "A = my.array[1,]"}
if (length(dim(my.array)) == 3){to_run = "A = my.array[1,,]"}
eval(parse(text=to_run))

回答1:


Self-modifying code is much more difficult to understand than to write. The example you gave has a perfectly valid R equivalent:

if (length(dim(my.array)) == 2) {
  A = my.array[1,]
} else if (length(dim(my.array)) == 3)
  A = my.array[1,,]


来源:https://stackoverflow.com/questions/20678930/why-is-it-a-bad-habit-to-parse-and-evaluate-a-string-code-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!