为什么这些表达方式不相同?

时间:2015-03-20 15:13:33

标签: r

设置

# returns the expression supplied to the first argument
get_expr <- function(x) as.expression(substitute(x))

identical(expression(a + 1), get_expr(a + 1))
# TRUE

(x <- get_expr({a<-1;b<-2}))
# expression({
#     a <- 1
#     b <- 2
# })

(y <- expression({a<-1;b<-2}))
# expression({
#     a <- 1
#     b <- 2
# })

str(x)
#  expression({     a <- 1     b <- 2 })
str(y)
#  expression({     a <- 1     b <- 2 })

all.equal(x, y)
# TRUE

问题

identical(x, y)
# FALSE

将任何默认参数更改为identical不会影响结果。

1 个答案:

答案 0 :(得分:11)

这些不是相同的,因为属性不同。

> str(x[[1]])
length 3 {  a <- 1; b <- 2 }
 - attr(*, "srcref")=List of 3
  ..$ :Class 'srcref'  atomic [1:8] 1 15 1 15 15 15 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b4f90> 
  ..$ :Class 'srcref'  atomic [1:8] 1 16 1 19 16 19 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b4f90> 
  ..$ :Class 'srcref'  atomic [1:8] 1 21 1 24 21 24 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b4f90> 
 - attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b4f90> 
 - attr(*, "wholeSrcref")=Class 'srcref'  atomic [1:8] 1 0 1 25 0 25 1 1
  .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b4f90> 
> str(y[[1]])
length 3 {  a <- 1; b <- 2 }
 - attr(*, "srcref")=List of 3
  ..$ :Class 'srcref'  atomic [1:8] 1 17 1 17 17 17 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b6ac0> 
  ..$ :Class 'srcref'  atomic [1:8] 1 18 1 21 18 21 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b6ac0> 
  ..$ :Class 'srcref'  atomic [1:8] 1 23 1 26 23 26 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b6ac0> 
 - attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b6ac0> 
 - attr(*, "wholeSrcref")=Class 'srcref'  atomic [1:8] 1 0 1 27 0 27 1 1
  .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x31b6ac0> 

这是由于{的使用,您可以通过简化示例看到:

> str(quote(a))
 symbol a
> str(quote({a}))
length 2 {  a }
 - attr(*, "srcref")=List of 2
  ..$ :Class 'srcref'  atomic [1:8] 1 11 1 11 11 11 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x1e940c8> 
  ..$ :Class 'srcref'  atomic [1:8] 1 12 1 12 12 12 1 1
  .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x1e940c8> 
 - attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x1e940c8> 
 - attr(*, "wholeSrcref")=Class 'srcref'  atomic [1:8] 1 0 1 13 0 13 1 1
  .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x1e940c8> 

?Paren也提供了一些指导。