To rename an object in R, we can use the assignment operator as follows:
new_name <- old_name
This syntax can be used to rename vectors, data frames, matrices, lists, and any other type of data object in R.
The following example shows how to use this syntax in practice.
Example: Rename Object in R
Suppose we have the following data frame called my_data in R:
#create data frame some_data <- data.frame(x=c(3, 4, 4, 5, 9), y=c(3, 8, 7, 10, 4), z=c(1, 2, 2, 6, 7)) #view data frame some_data x y z 1 3 3 1 2 4 8 2 3 4 7 2 4 5 10 6 5 9 4 7
We can use the assignment operator to rename this data frame to new_data:
#rename data frame
new_data <- some_data
#view data frame
new_data
x y z
1 3 3 1
2 4 8 2
3 4 7 2
4 5 10 6
5 9 4 7
Notice that we’re able to type new_data to view this data frame now.
However, it’s important to note that the old name some_data can still be used to reference this data frame:
#view data frame
some_data
x y z
1 3 3 1
2 4 8 2
3 4 7 2
4 5 10 6
5 9 4 7
To remove this name from our R environment, we can use the rm() function:
#remove old name of data frame
rm(some_data)
Now if we attempt to use the old name, the object will no longer be in an our environment:
#attempt to use old name to view data frame
some_data
Error: object 'some_data' not found
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Rename Files in R
How to Rename Factor Levels in R
How to Rename Data Frame Columns in R