错误:分配目标扩展为非语言对象

栏目: R语言 · 发布时间: 5年前

内容简介:http://stackoverflow.com/questions/27662162/error-in-my-code-target-of-assignment-expands-to-non-language-object

我收到错误

Error in <my code> : target of assignment expands to non-language object

要么

Error in <my code> : invalid (do_set) left-hand side to assignment

要么

Error in <my code> : invalid (NULL) left side of assignment

这是什么意思,我该如何防止呢?

当您尝试将 assign a value 修改为不存在的变量,或者R不能作为 name

处理时,会出现这些错误.(名称是一个变量类型,用于保存变量名.)

要重现错误,请尝试:

1:2 <- 1
## Error in 1:2 <- 1 : target of assignment expands to non-language object

1 <- 1
## Error in 1 <- 1 : invalid (do_set) left-hand side to assignment

mean() <- 1
## Error in mean() <- 1 : invalid (NULL) left side of assignment

(你可以猜测NULL<- 1返回的三个错误中的哪一个) R的一个鲜为人知的功能是可以为字符串赋值:

"x" <- 1 # same as x <- 1

如果您使用例如 paste 使用更复杂的表达式尝试构造字符串,则此操作不起作用.

paste0("x", "y") <- 1
## Error: target of assignment expands to non-language object

看到

解决方案是使用 assign

assign(paste0("x", "y"), 1)

出现这种情况的常见情况是尝试分配给数据帧列时.通常会尝试将()一起粘贴在分配的左手,即

paste0("my_dataframe$","my_column") <- my_value

通常,这里的最佳解决方案不是诉诸于获取或分配,而是要记住,我们可以使用[or [[operator:

x <- "my_column"
my_dataframe[,x] <- value #or...
my_dataframe[[x]] <- value

类似地,您无法分配给 get 的结果.

get("x") <- 1
## Error in get("x") <- 1 : 
##   target of assignment expands to non-language object

解决方案是

assign("x", 1)

或简单地

"x" <- 1

Using get() with replacement functions 处理更复杂的情况,结合替换功能.

另请参阅 Assignment in R language 的答案,详细介绍了与作业相关的一些奥秘,特别是R语言定义对 Subset Assignment 的描述.

http://stackoverflow.com/questions/27662162/error-in-my-code-target-of-assignment-expands-to-non-language-object


以上所述就是小编给大家介绍的《错误:分配目标扩展为非语言对象》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Rust

Programming Rust

Jim Blandy / O'Reilly Media / 2016-8-25 / GBP 47.99

This practical book introduces systems programmers to Rust, the new and cutting-edge language that’s still in the experimental/lab stage. You’ll learn how Rust offers the rare and valuable combination......一起来看看 《Programming Rust》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

随机密码生成器
随机密码生成器

多种字符组合密码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试