Changing Column and Row Names in a DataFrame in R
Overview
When writing complex code using data frames in R, there are situations where you need to change the default column names because they can become confusing.
names()
For example, looking at the data frame above, if no specific mention is made, vague and indistinct column names like V1, V2, V3 are given. By applying the names() function, you can return the column names, and conversely, you can change the column names by directly inserting strings.
Simply by assigning them, you can see that V1, V2, V3 have been changed to un, du, tri, respectively. Of course, to do this, you must provide a vector of strings with the same number of elements as the original columns. While this isn’t much of an issue for small-scale data handling, it becomes cumbersome with big data that easily surpasses 50 independent variables.
Indexing
If you don’t want to supply a vector but rather change a specific column only, you can do it through indexing as follows.
You can see that the second column name, du, has been neatly changed to two.
dimnames()
Although not often used, when changing the row names, the dimnames()
function is used. dimnames()
is a function that returns or references the names of the dimensions as a list.
While not as straightforward as changing column names, you can see that the row names have been neatly changed.
Code
Below is the example code.
example <- as.data.frame(matrix(c(5,10,3,12,15,78),nrow=2)); example
names(example)<-c("un","du","tri"); example
names(example)[2]<-"two"; example
dimnames(example) <- list(row=c("첫줄","둘째줄"),col=names(example)); example