Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I name the "row names" column in r

Tags:

r

I'm working with a data frame in r where my row names are meaningful. Hence, I would like to give the column of row names a name. How do I do this?

like image 474
Ben Avatar asked Jul 07 '13 17:07

Ben


People also ask

How do I label a column name in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I get the row name in R?

To find the column names and row names in an R data frame based on a condition, we can use row. names and colnames function. The condition for which we want to find the row names and column names can be defined inside these functions as shown in the below Examples.


2 Answers

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column myDF <- cbind(Row.Names = rownames(myDF), myDF) myDF  #           Row.Names id val vr2 # row_one     row_one  A   1  23 # row_two     row_two  A   2  24 # row_three row_three  B   3  25 # row_four   row_four  C   4  26 

If you want to then remove the original rownames:

rownames(myDF) <- NULL myDF #   Row.Names id val vr2 # 1   row_one  A   1  23 # 2   row_two  A   2  24 # 3 row_three  B   3  25 # 4  row_four  C   4  26 


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF) names(dimnames(myMat)) <- c("Names.of.Rows", "") myMat  # Names.of.Rows id  val vr2  #   row_one   "A" "1" "23" #   row_two   "A" "2" "24" #   row_three "B" "3" "25" #   row_four  "C" "4" "26" 
like image 114
Ricardo Saporta Avatar answered Oct 11 '22 16:10

Ricardo Saporta


The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble) rownames_to_column(mtcars, var="das_Auto") %>% head 

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb 1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 
like image 37
Joe Avatar answered Oct 11 '22 15:10

Joe