Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename the rows of a dataframe on the fly?

Tags:

dataframe

r

I love to rename a vector on the fly with setNames (by on-the-fly I mean a function that returns the object):

my_vector <- c(1,2,3)
setNames(my_vector, c("a","b","c"))
# a b c
# 1 2 3

That works for dataframe column names as well

my_df <- data.frame(matrix(1:9, nrow=3))
setNames(my_df, c("a","b","c"))
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

Is there a way to do the same with the row names? I thought this would work, but it doesn't:

t(setNames(t(my_df), c("a","b","c")))
like image 802
nachocab Avatar asked Oct 23 '13 13:10

nachocab


People also ask

How do I rename a row in a DataFrame?

Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe.

How do you name rows in pandas?

Using rename() This is the most preferred method as we can change both the column and row index using this method. We just pass in the old and new values as a dictionary of key-value pairs to this method and save the data frame with a new name.


1 Answers

I think what you mean by on-the-fly is you want the function to return the modified object. Since rownames<- does not do that for you, you will have to define your own function:

setRowNames <- function(df, row.names) {
   rownames(df) <- row.names
   df
}

You can have that function definition at the top of your script, or even hide it in your Rprofile or Rprofile.site (see ?Startup if you are not familiar). Then inside your code, use setRowNames(my_df, c("a", "b", "c")). It is concise, flexible, and reads nicely.


t(setNames(t(my_df), c("a","b","c"))) does not work because transposing a data.frame gives you a matrix which does not have names but rownames and colnames.

like image 183
flodel Avatar answered Sep 20 '22 21:09

flodel