gpt4 book ai didi

r - 为什么这些表达不相同?

转载 作者:行者123 更新时间:2023-12-04 17:08:53 25 4
gpt4 key购买 nike

设置

# 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不影响结果。

最佳答案

这些并不相同,因为属性不同。

> 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也提供了一些指导。

关于r - 为什么这些表达不相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29169871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com