This function can be used on any data.frame
, list
or character vector to format their names or values. It supports snake case and camel case.
format_names(
x,
...,
snake_case = FALSE,
camelCase = FALSE,
tolower = FALSE,
toupper = FALSE
)
a data.frame
, list
or character
vector
when x
is a data.frame
: new column names to set, which can be named (in the form old = "new"
). The original column names do not need to be quoted, see Examples.
logical to indicate whether the column names must be in snake case. This will have no effect on manually set column names.
logical to indicate whether the column names must be in camel case. This will have no effect on manually set column names.
logical to indicate whether the column names must be lower/upper case. This will have no effect on manually set column names.
df <- data.frame(Name.341ABC = "value",
name_123def = "value",
This.is.a.column = "value")
format_names(df, snake_case = TRUE)
#> name_341_abc name_123def this_is_a_column
#> 1 value value value
format_names(df, camelCase = TRUE)
#> name341ABC name123def thisIsAColumn
#> 1 value value value
format_names(df, letters[1:3])
#> a b c
#> 1 value value value
format_names(df, This.is.a.column = "a_new_colname")
#> Name.341ABC name_123def a_new_colname
#> 1 value value value
rownames(mtcars) <- format_names(rownames(mtcars), snake_case = TRUE)
mtcars[, 1:5]
#> mpg cyl disp hp drat
#> mazda_rx_4 21.0 6 160.0 110 3.90
#> mazda_rx_4_wag 21.0 6 160.0 110 3.90
#> datsun_710 22.8 4 108.0 93 3.85
#> hornet_4_drive 21.4 6 258.0 110 3.08
#> hornet_sportabout 18.7 8 360.0 175 3.15
#> valiant 18.1 6 225.0 105 2.76
#> duster_360 14.3 8 360.0 245 3.21
#> merc_240_d 24.4 4 146.7 62 3.69
#> merc_230 22.8 4 140.8 95 3.92
#> merc_280 19.2 6 167.6 123 3.92
#> merc_280_c 17.8 6 167.6 123 3.92
#> merc_450_se 16.4 8 275.8 180 3.07
#> merc_450_sl 17.3 8 275.8 180 3.07
#> merc_450_slc 15.2 8 275.8 180 3.07
#> cadillac_fleetwood 10.4 8 472.0 205 2.93
#> lincoln_continental 10.4 8 460.0 215 3.00
#> chrysler_imperial 14.7 8 440.0 230 3.23
#> fiat_128 32.4 4 78.7 66 4.08
#> honda_civic 30.4 4 75.7 52 4.93
#> toyota_corolla 33.9 4 71.1 65 4.22
#> toyota_corona 21.5 4 120.1 97 3.70
#> dodge_challenger 15.5 8 318.0 150 2.76
#> amc_javelin 15.2 8 304.0 150 3.15
#> camaro_z_28 13.3 8 350.0 245 3.73
#> pontiac_firebird 19.2 8 400.0 175 3.08
#> fiat_x_1_9 27.3 4 79.0 66 4.08
#> porsche_914_2 26.0 4 120.3 91 4.43
#> lotus_europa 30.4 4 95.1 113 3.77
#> ford_pantera_l 15.8 8 351.0 264 4.22
#> ferrari_dino 19.7 6 145.0 175 3.62
#> maserati_bora 15.0 8 301.0 335 3.54
#> volvo_142_e 21.4 4 121.0 109 4.11
format_names(list(a = 1, b = 2), c("new_1", "new_2"))
#> $new_1
#> [1] 1
#>
#> $new_2
#> [1] 2
#>
if (FALSE) { # \dontrun{
library(dplyr)
starwars %>%
format_names(camelCase = TRUE) %>% # new column names
mutate(name = name %>%
format_names(name,
snake_case = TRUE)) # new values in column
} # }