I often use R's setNames
function in a magrittr pipeline or elsewhere to fix the names of an object on the fly:
library(magrittr)
mytable %>% setNames(c("col1", "col2", "col3")) %>% ...[more analysis]
Are there equivalent functions for colnames and rownames? Something like setColnames
?
names() creates name attributes where as colnames() simply names the columns. Create a temp variable. Create the names. temp object.
colnames() function in R Language is used to set the names to columns of a matrix. Syntax: colnames(x) <- value.
Method 1: using colnames() methodcolnames() 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.
It’s not pretty, but the following works:
mytable %>% `colnames<-`(c("col1", "col2", "col3")) %>% ...[more analysis]
This uses the fact that an assignment of the form colnames(x) <- foo
is actually calling a function `colnames<-`(x, foo)
. The backticks around the name are necessary since colnames<-
is not ordinarily a valid identifier in R (but between backticks it is).
So you don’t need any aliases.
magrittr
provides several "aliases" (see ??Aliases
), including set_colnames
(equivalent to `colnames<-`
) and set_rownames
(equivalent to `rownames<-`
).
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