Select Page

How to Solve R Error: invalid (do_set) left-hand side to assignment

by | Programming, R, Tips

This error occurs if you try to create a variable with a name beginning with a number.

You can solve this error by ensuring the variable starts with a letter or a dot.

You can see the documentation for syntactically valid names by typing the following command:

?make.names

This tutorial will go through the error in detail and how to solve it with code examples.


Example

Let’s look at an example to reproduce the error.

# Attempt to create data frame

2 <- data.frame(x=c(rnorm(10)),
                  y=c(rnorm(10)))

2

Let’s run the code to see what happens:

Error in 2 <- data.frame(x = c(rnorm(10)), y = c(rnorm(10))) : 
  invalid (do_set) left-hand side to assignment

The error occurs because the variable name is a number.

Solution

We can solve this error by ensuring the variable names starts with a letter or a dot. Let’s look at the revised code:

# Attempt to create data frame with name starting with a letter

df2 <- data.frame(x=c(rnorm(10)),
                  y=c(rnorm(10)))

df2

Let’s run the code to see the result.

             x            y
1   1.487757090  1.052458495
2  -0.001891901 -1.305063566
3   1.381020790 -0.692607634
4  -0.380213631  0.602648854
5   0.184136230 -0.197753074
6  -0.246895883 -1.185874517
7  -1.215560910 -2.005512989
8   1.561405098  0.007509885
9   0.427310197  0.519490356
10 -1.201023506 -0.746295471

We can also use a data frame that starts with a dot. Let’s look at the revised code:

.df2 <- data.frame(x=c(rnorm(10)),
                  y=c(rnorm(10)))

.df2

Let’s run the code to see the result:

           x          y
1   0.7264546 -0.8174286
2   0.7136567  0.6758935
3  -0.6500629 -0.2154811
4   1.4986962 -0.1146497
5  -1.4358281 -0.2022654
6  -2.1613182  0.4064927
7   0.3952199  0.6567724
8  -0.3948340  0.1061908
9  -0.3097584 -0.1843974
10  1.3308266  0.9460342

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!