在名称<-()内创建对象会出错。怎么解释呢?

发布于 2024-09-27 14:54:26 字数 623 浏览 3 评论 0 原文

x <- list(12, 13)
names(y <- x) <- c("a", "b")

给出了错误:

Error in names(y <- x) <- c("a", "b") : object 'y' not found

任何人都可以解释为什么吗?

根据 R 的求值规则,y <- x 应该在 name<- 的父框架内求值。所以 y 应该在全局环境中创建。

谢谢。

[update] 如果对象 y 已经存在于全局环境中,则错误为:

Error in names(y <- x) <- c("a", "b") : could not find function "<-<-"

[update2] 这是我今天遇到的另一个构造。

(X <- matrix(0, nrow = 10, ncol = 10))[1:3] <- 3:5
Error during wrapup: object 'X' not found

This

x <- list(12, 13)
names(y <- x) <- c("a", "b")

gives the error:

Error in names(y <- x) <- c("a", "b") : object 'y' not found

Can anyone explain why?

According to R's rules of evaluation y <- x should be evaluated inside the parent frame of names<-. So y should be created in global environment.

Thanks.

[update] If object y is already present in the global environment, then the error is:

Error in names(y <- x) <- c("a", "b") : could not find function "<-<-"

[update2] Here it is, another construct, which I encountered today.

(X <- matrix(0, nrow = 10, ncol = 10))[1:3] <- 3:5
Error during wrapup: object 'X' not found

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随遇而安 2024-10-04 14:54:26

这与 <- 递归地转换 LHS 的方式有关,将 "<-" 附加到函数名称以获取替换形式。第一个参数经过特殊处理。请注意最后两者之间的区别:

x <- a <- 1
`f<-` <- function(x, a, value) x
f(x, a <- 2) <- 2
f(x <- 2, a) <- 2
# Error in f(x <- 2, a) <- 2 : could not find function "<-<-"

对于您想要执行的操作,我无论如何都会使用 setNames

This is related to the way that <- recursively transforms the LHS, appending "<-" to the names of functions to get the replacement form. The first argument is treated specially. Note the difference between the last two:

x <- a <- 1
`f<-` <- function(x, a, value) x
f(x, a <- 2) <- 2
f(x <- 2, a) <- 2
# Error in f(x <- 2, a) <- 2 : could not find function "<-<-"

For what you're trying to do, I'd use setNames anyway.

老街孤人 2024-10-04 14:54:26

这可能是由于惰性评估造成的。当在一行中执行多个任务时,几乎无法保证事情将以什么顺序完成。显然,在这种情况下,它会在评估作业之前尝试找到 y。如果您只询问名称,则分配 y。

最好分两步完成这些类型的事情,这样您就可以放心,第一步在第二步需要结果之前完成。

This is probably due to lazy evaluation. There is little guarentee what order things will be done in when doing multiple tasks in one line. Apparently in this case it tries to find y before evaluating the assignment. If you just ask for the names, then y is assigned.

It is best to do these types of things in 2 steps so you can be assured that the first is done before the second needs the results.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文