Thursday, 15 November 2018

r - Changing column names of a data frame

There are a couple options with dplyr::rename() and dplyr::select():


library(dplyr)
mtcars %>%
tibble::rownames_to_column('car_model') %>% # convert rowname to a column. tibble must be installed.
select(car_model, est_mpg = mpg, horse_power = hp, everything()) %>% # rename specific columns and reorder
rename(weight = wt, cylinders = cyl) %>% # another option for renaming specific columns that keeps everything by default
head(2)
car_model est_mpg horse_power cylinders disp drat weight qsec vs am gear carb
1 Mazda RX4 21 110 6 160 3.9 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21 110 6 160 3.9 2.875 17.02 0 1 4 4

There are also three scoped variants of dplyr::rename(): dplyr::rename_all() for all column names, dplyr::rename_if() for conditionally targeting column names, and dplyr::rename_at() for select named columns. The following example replaces spaces and periods with an underscore and converts everything to lower case:


iris %>%
rename_all(~gsub("\\s+|\\.", "_", .)) %>%
rename_all(tolower) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa

dplyr::select_all() can also be used in a similar way:


iris %>%
select_all(~gsub("\\s+|\\.", "_", .)) %>%
select_all(tolower) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...