You can use the **make.names **function in R to create syntactically valid names out of character vectors.

This function uses the following basic syntax:

make.names(names, unique = FALSE)

where:

**names**: Character vector to be coerced to syntactically valid names.**unique**: Whether or not to create unique names. Default is FALSE.

The following examples show how to use this function in different scenarios.

**Example 1: Create Valid Names for Vector**

Suppose we have the following vector of numeric values:

#create vector of numeric values numeric_values <- c(1, 1, 4, 7, 8) #create syntactically valid names from numeric values make.names(numeric_values) [1] "X1" "X1" "X4" "X7" "X8"

R defines “valid names” as names that start with a character or dot.

Thus, to convert each of the numeric values in the vector to a valid name, R simply adds an “X” in front of each value.

Note that two of the names (“X1”) are the exact same.

To force the names to be unique, we can specify **unique=TRUE**:

#create vector of numeric values numeric_values <- c(1, 1, 4, 7, 8) #create syntactically valid names from numeric values make.names(numeric_values, unique=TRUE) [1] "X1" "X1.1" "X4" "X7" "X8"

Notice that each name is now unique.

**Example 2: Create Valid Names for Matrix**

Suppose we have the following matrix in R:

#create matrix mat <- matrix(c(1, 2, 3, 7, 2, 4, 4, 6, 0, 1), ncol=2) #view matrix mat [,1] [,2] [1,] 1 4 [2,] 2 4 [3,] 3 6 [4,] 7 0 [5,] 2 1 #view column names of matrix colnames(mat) NULL

Notice that the matrix currently doesn’t have any column names.

However, we can use the **make.names()** function to quickly create column names:

#create column names for matrix colnames(mat) <- make.names(1:ncol(mat)) #view updated matrix mat X1 X2 [1,] 1 4 [2,] 2 4 [3,] 3 6 [4,] 7 0 [5,] 2 1

Notice that the matrix now has “X1” and “X2” as the column names.

If we’d like, we can now extract values from a specific column in the matrix using the column name:

#view values in "X1" column of matrix mat[, 'X1'] [1] 1 2 3 7 2

Also 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 perform other common operations in R:

How to Change Row Names in R

How to Loop Through Column Names in R

How to Use the names Function in R