eval(call) different from typing the expre

2020-07-18 02:13发布

问题:

given the call below,
why does eval(call) yield results different from simply typing the expression right 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've even tried calling eval on the dput of the expression being converted to the 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

回答1:

In x, you specify Mat as a matrix.

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

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

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

But this does not tell the whole story. Have a look at the structure of the call.

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

You can see that Mat is actually represented as a matrix. The output of theCall is not identical to its internal structure. When you run the command that is returned by str, you can see the following data frame.

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

Not surprisingly, this result is identical to the one of 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


标签: r eval