Home » How to Fix: attempt to set ‘colnames’ on an object with less than two dimensions

How to Fix: attempt to set ‘colnames’ on an object with less than two dimensions

by Erma Khan

One error message you may encounter when using R is:

Error in `colnames

This error usually occurs when you attempt to use the colnames() function to set the column names on an object that is not a data frame or matrix.

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

How to Reproduce the Error

Suppose we have the following data frame in R:

#create data frame
df frame(team=c('A', 'A', 'C', 'B', 'C', 'B', 'B', 'C', 'A'),
                 points=c(12, 8, 26, 25, 38, 30, 24, 24, 15),
                 rebounds=c(10, 4, 5, 5, 4, 3, 8, 18, 22))

#view data frame
df

  team points rebounds
1    A     12       10
2    A      8        4
3    C     26        5
4    B     25        5
5    C     38        4
6    B     30        3
7    B     24        8
8    C     24       18
9    A     15       22

Now suppose we attempt to add a new row to the end of the data frame:

#define new row to add to end of data frame
new_row #attempt to define column names for new row
colnames(new_row) 

We receive an error because we used the colnames() function on a vector instead of a data frame or matrix.

How to Fix the Error

To avoid this error, we need to make sure that we’re using the colnames() function with a data frame:

For example, we can use the following code to add a new row to the end of the data frame

#define new row to add to end of data frame
new_row frame('D', 15, 11)

#define column names for new row
colnames(new_row) #add new row to end of data frame
df #view updated data frame
df

   team points rebounds
1     A     12       10
2     A      8        4
3     C     26        5
4     B     25        5
5     C     38        4
6     B     30        3
7     B     24        8
8     C     24       18
9     A     15       22
10    D     15       11

This time we don’t receive any error because we used the colnames() function to define the column names of a data frame instead of a vector.

We’re then able to successfully use rbind() to bind the new row to the end of the existing data frame.

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

Related Posts