liveBook · Manning

Colnames() function

As explained in Statistics Slam Dunk

The colnames() function in R gets or sets the column names of a matrix-like object such as a data frame.

Use R’s base colnames() function to get or replace the column names of a matrix-like object, including a data frame or tibble. When replacing every name, provide a character vector whose length equals the object’s number of columns. section 6.4.6

Rename a results table

After grouping tied-at-halftime NBA games, replace tbl21’s difficult logical-expression headers with compact names: colnames(tbl21) <- c('HHH', 'HRH', 'RHH', 'RRR', 'RHR', 'HRR', 'count') head(tbl21, n = 1) The resulting columns identify quarter-and-game outcomes, followed by their counts. section 6.4.6

colnames(tbl21) <- c('HHH', 'HRH', 'RHH', 'RRR', 'RHR', 'HRR', 'count')
head(tbl21, n = 1)
## # A tibble: 1 × 7
## # Groups:   HHH, HRH, RHH, RRR, RHR [1]
##   HHH   HRH   RHH   RRR   RHR   HRR   count
##   <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <int>
## 1 FALSE FALSE FALSE FALSE FALSE TRUE      6

Inspect the renamed headers and first data row before continuing with type conversion and table reshaping. section 6.4.6

How Statistics Slam Dunk covers it

How deep it goes
Defines full replacement and vector-length requirements, but does not detail column-name retrieval or advanced naming rules.
Examples
Uses tbl21, six outcome abbreviations, a count column, and head(tbl21, n = 1) to inspect the renamed table.
What it assumes
Assumes a matrix-like object and a character vector, while warning against spaces and special characters in names.
What you can do after
Apply it via base R to replace a table’s complete set of column names and inspect the result.
How it connects
Connects column naming with tibbles, rename(), c(), head(), as.numeric(), and data wrangling.

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.