Ryan C. Thompson
Ryan C. Thompson

Reputation: 42090

setNames equivalent for colnames and rownames for use in pipe

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?

Upvotes: 11

Views: 1637

Answers (3)

John Maindonald
John Maindonald

Reputation: 191

Note that setNames() can be used if the object is converted to a data frame. The following uses the new R pipe operator:

    matrix(1:6, ncol=2) |> as.data.frame() |>
        setNames(c("One23","Four56")) -> thatsIt

The right pointing assignment arrow seems more in the spirit of pipes than a preceding left pointing assignment arrow. Or, to print the result:

    matrix(1:6, ncol=2) |> as.data.frame() |>
        setNames(c("One23","Four56")) |> print()
      One23 Four56
    1     1      4
    2     2      5
    3     3      6

Upvotes: 0

Henrik
Henrik

Reputation: 67828

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

Upvotes: 13

Konrad Rudolph
Konrad Rudolph

Reputation: 546133

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.

Upvotes: 6

Related Questions