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")))
Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe.
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.
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.
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