eval(call)与在控制台中键入表达式不同 [英] eval(call) different from typing the expression into the console
问题描述
鉴于下面的call
,
为什么eval(call)
产生的结果与仅在控制台中直接键入表达式不同
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
我什至尝试在要转换为调用的表达式的dput上调用eval,但仍然无法获得与eval(theCall)相同的结果
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
推荐答案
在x
中,将Mat
指定为矩阵.
x <- list(Vect=seq(3), Mat=matrix(seq(9), ncol=3))
theCall <- as.call(c(expression(data.frame), x))
但是,当您查看theCall
的输出时,看起来Mat
是一个具有1到9的数字的向量.
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)))
您可以看到Mat
实际上表示为矩阵. theCall
的输出与其内部结构不同.当您运行由str
返回的命令时,您会看到以下数据框.
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
毫不奇怪,此结果与eval(theCall)
的结果相同.
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
这篇关于eval(call)与在控制台中键入表达式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!