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?
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.
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.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With