Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setNames equivalent for colnames and rownames for use in pipe

Tags:

r

magrittr

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?

like image 514
Ryan C. Thompson Avatar asked Feb 07 '15 00:02

Ryan C. Thompson


People also ask

What is the difference between names and Colnames in R?

names() creates name attributes where as colnames() simply names the columns. Create a temp variable. Create the names. temp object.

What does Colnames mean in R?

colnames() function in R Language is used to set the names to columns of a matrix. Syntax: colnames(x) <- value.

How do I use Colnames in R?

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.


2 Answers

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.

like image 160
Konrad Rudolph Avatar answered Oct 12 '22 13:10

Konrad Rudolph


magrittr provides several "aliases" (see ??Aliases), including set_colnames (equivalent to `colnames<-`) and set_rownames (equivalent to `rownames<-`).

like image 39
Henrik Avatar answered Oct 12 '22 12:10

Henrik