Eval (call) is different from entering an expression in the console

given callbelow
why eval(call)gives results other than just typing the expression directly into the console

x <- list(Vect=seq(3), Mat=matrix(seq(9), ncol=3))

## This call came from the source to `as.data.table.list()`
theCall <- as.call(c(expression(data.frame), x))

theCall
# data.frame(Vect = 1:3, Mat = 1:9)

data.frame(Vect=1:3, Mat=1:9)
#   Vect Mat
# 1    1   1
# 2    2   2
# 3    3   3
# 4    1   4
# 5    2   5
# 6    3   6
# 7    1   7
# 8    2   8
# 9    3   9

eval(theCall)
#   Vect Mat.1 Mat.2 Mat.3
# 1    1     1     4     7
# 2    2     2     5     8
# 3    3     3     6     9

eval(parse(text=capture.output(theCall)))
#   Vect Mat
# 1    1   1
# 2    2   2
# 3    3   3
# 4    1   4
# 5    2   5
# 6    3   6
# 7    1   7
# 8    2   8
# 9    3   9

I even tried calling eval on the dput of an expression that converts to a call, and still cannot get the same results as eval (theCall)

dput(c(expression(data.frame), x))
# structure(expression(data.frame, Vect = 1:3, Mat = 1:9), .Names = c("", "Vect", "Mat"))

eval(as.call(structure(expression(data.frame, Vect = 1:3, Mat = 1:9), .Names = c("", "Vect", "Mat"))))
#   Vect Mat
# 1    1   1
# 2    2   2
# 3    3   3
# 4    1   4
# 5    2   5
# 6    3   6
# 7    1   7
# 8    2   8
# 9    3   9

+4
source share
1 answer

In xyou indicate Matas a matrix.

x <- list(Vect=seq(3), Mat=matrix(seq(9), ncol=3))
theCall <- as.call(c(expression(data.frame), x))

However, when you look at the output theCall, it looks like Mat- it is a vector with numbers from 1 to 9.

theCall
# data.frame(Vect = 1:3, Mat = 1:9)

But that does not tell the whole story. Look at the call structure.

str(theCall)
# language data.frame(Vect = 1:3, Mat = structure(1:9, .Dim = c(3L, 3L)))

, Mat . theCall . , str, .

data.frame(Vect = 1:3, Mat = structure(1:9, .Dim = c(3L, 3L)))
#   Vect Mat.1 Mat.2 Mat.3
# 1    1     1     4     7
# 2    2     2     5     8
# 3    3     3     6     9

, eval(theCall).

eval(theCall)
#   Vect Mat.1 Mat.2 Mat.3
# 1    1     1     4     7
# 2    2     2     5     8
# 3    3     3     6     9
+5

All Articles