<我的代码>中的错误:分配目标扩展为非语言对象 [英] 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
这是什么意思,我该如何预防?
What does it mean, and how do I prevent it?
推荐答案
当您尝试 name
. (名称是包含变量名称的变量类型.)
These errors occur when you try to assign a value to a variable that doesn't exist, or that R can't treat as a name
. (A name is a variable type that holds a variable 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
返回的三个错误中的哪一个吗?)
(Can you guess which of the three errors NULL <- 1
returns?)
R的一个鲜为人知的功能是您可以为字符串分配值:
A little-known feature of R is that you can assign values to a string:
"x" <- 1 # same as x <- 1
如果您尝试使用更复杂的表达式(例如 paste
.
This doesn't work if you try and construct the string using a more complex expression using, for example, paste
.
paste0("x", "y") <- 1
## Error: target of assignment expands to non-language object
请参见
使用"paste"创建变量名称,在R中?和
如何动态命名变量?
解决方案是使用 assign
:
The solution to this is to use assign
:
assign(paste0("x", "y"), 1)
出现这种情况的常见情况是尝试分配给数据帧的列.通常会尝试将paste()
分配到作业的左手,即
A common scenario in which this comes up is when trying to assign to columns of data frames. Often an attempt will be made to paste()
together the left hand of the assignment, i.e.
paste0("my_dataframe$","my_column") <- my_value
这里的最佳解决方案通常是不是诉诸get
或assign
,但要记住,我们可以使用[
或[[
通过字符变量引用数据帧列运算符:
Often the optimal solution here is not to resort to get
or assign
but to remember that we can refer to data frame columns by character variables using the [
or [[
operator:
x <- "my_column"
my_dataframe[,x] <- value #or...
my_dataframe[[x]] <- value
类似地,您不能将结果分配给 get
Similarly, you can't assign to the result of get
.
get("x") <- 1
## Error in get("x") <- 1 :
## target of assignment expands to non-language object
解决方案是
assign("x", 1)
或者简单地
"x" <- 1
将get()与替换函数一起使用可处理更复杂的get
案例,并带有替换函数.
Using get() with replacement functions deals with a more complex case of get
combined with a replacement function.
使用magrittr
软件包时,意外拖尾管道运算符也可能导致此错误.
When using the magrittr
package, accidental trailing pipe operators can cause this error too.
library(magrittr)
x <- 1 %>%
y <- 2
## Error in 1 %>% y <- 2 :
## target of assignment expands to non-language object
另请参见 R语言中的赋值,其答案详细介绍了一些与赋值有关的秘诀,特别是R语言定义的说明子集分配.
See also Assignment in R language whose answers detail some of the arcana related to assignment, particularly the R language definition's description of Subset Assignment.
这篇关于<我的代码>中的错误:分配目标扩展为非语言对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!