How to Fix in R: invalid (do_set) left-hand side to assignment


One error message you may encounter when using R is:

Error in 5 <- read.table("data.txt") : 
  invalid (do_set) left-hand side to assignment

This error occurs when you attempt to create a variable in R that starts with a number.

By default, R only allows you to define variable names that start with either a character or a dot.

The following example shows how to resolve this error in practice.

How to Reproduce the Error

Suppose I attempt to use the read.table() function to read a file into R:

#attempt to read text file into R
5 <- read.table("data.txt")

Error in 5 <- read.table("data.txt") : 
  invalid (do_set) left-hand side to assignment

I receive an error because I attempted to create a variable name that started with a number.

How to Avoid the Error

To avoid the error, I must use a variable name that starts with a character or a dot.

For example, I could use the following variable name that starts with a character:

#read text file into R
data5 <- read.table("data.txt")

#view contents of text file
data5

   V1 V2
1   1  4
2   3  4
3   2  5
4   7  9
5   9  1
6   6  3
7   4  4

Or I could even use the following variable name that starts with a dot:

#read text file into R
.data5 <- read.table("data.txt")

#view contents of text file
.data5

   V1 V2
1   1  4
2   3  4
3   2  5
4   7  9
5   9  1
6   6  3
7   4  4

Once again I don’t receive an error because I didn’t start the variable name with a character.

Note that you can type the following into R to read the complete documentation on how to create syntactically valid names:

?make.names

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix in R: Arguments imply differing number of rows
How to Fix in R: error in select unused arguments
How to Fix in R: replacement has length zero

Leave a Reply

Your email address will not be published. Required fields are marked *