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

I was 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 this a bad habit?

It seems to me that this is a fairly flexible way of programming, since we can build our code in iterative order by inserting character strings together. For example, it makes it easy to process objects of various sizes, 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
source share
1 answer

Self-modifying code is much harder to understand than writing. 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,,]
+2
source

All Articles