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

Richie Cotton picture Richie Cotton · Dec 26, 2014 · Viewed 55.2k times · Source

I received the error

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

or

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

or

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

What does it mean, and how do I prevent it?

Answer

Richie Cotton picture Richie Cotton · Dec 26, 2014

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.)

To reproduce the errors, try:

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

(Can you guess which of the three errors NULL <- 1 returns?)


A little-known feature of R is that you can assign values to a string:

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

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

See

Create a variable name with "paste" in R? and
How to name variables on the fly?

The solution to this is to use assign:

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

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

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

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

The solution is either

assign("x", 1)

or simply

"x" <- 1

Using get() with replacement functions deals with a more complex case of get combined with a replacement function.


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

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.