Dplyr application renamed to all columns using pipe operator

I am working with an imported dataset that corresponds to the extract below:

set.seed(1)
dta <- data.frame("This is Column One" = runif(n = 10),
                     "Another amazing Column name" = runif(n = 10),
                     "!## This Columns is so special€€€" = runif(n = 10),
                    check.names = FALSE)

I am doing some cleaning up of this data with dplyr, and I would like to change the column names to parse them and remove the punctuation as a second step. What I have tried so far:

dta_cln <- dta %>% 
    rename(make.names(names(dta)))

generates an error:

> dta_clean <- dta %>% 
+     rename(make.names(names(dta)))
Error: All arguments to rename must be named.

Desired Result

What I wanted to achieve can be done in the database:

names(dta) <- gsub("[[:punct:]]","",make.names(names(dta)))

which will return:

> names(dta)
[1] "ThisisColumnOne"          "AnotheramazingColumnname" "XThisColumnsissospecial"

I want to achieve the same effect, but using dyplrand %>%.

+9
source share
4 answers

, , , , , .

Dplyr

dplyr 0.6.0 , rename_all:

  dta %>% 
    rename_all(funs(gsub("[[:punct:]]", "", make.names(names(dta)))))

, . dplyr, :

  • rename_at
  • rename_if

( ), :

library(janitor)

dta %>% 
  clean_names()

:

[1] "this_is_column_one"  "another_amazing_column_name"  "x_this_columns_is_so_special"

snake_case, CamelCase, clean_names , . , snakecase to_big_camel_case() rename_all...

+16
mtcars %>% 
  data.table::setnames(
    old = mtcars %>% names(),
    new = mtcars %>% names() %>% paste0("_new_name")
  )

setnames data.table . old new .

mtcars %>% names() mtcars %>%, names(mtcars). .

pipe %>% , paste0. , .

+2

You can also try this.

set.seed(1)
dta <- data.frame("This is Column One" = runif(n = 10),
                 "Another amazing Column name" = runif(n = 10),
                 "!## This Columns is so special€€€" = runif(n = 10),
                check.names = FALSE)

dta <- dta  %>% 
  setNames(gsub("[^[:alnum:] ]", perl = TRUE,
            "",
            names(.))) %>% 
  setNames(gsub("(\\w)(\\w*)",
            "\\U\\1\\L\\2",
            perl = TRUE,
            names(.)))

names(dta)
[1] "This Is Column One"          "Another Amazing Column Name" " This Columns Is So Special"
+1
source

Set the column names using the channel as follows:

iris %>% 'colnames<-'(c("newcol1", "newcol2", "newcol3", "newcol4", "newcol5"))

Which returns

    newcol1 newcol2 newcol3 newcol4    newcol5
1       5.1     3.5     1.4     0.2     setosa
2       4.9     3.0     1.4     0.2     setosa
3       4.7     3.2     1.3     0.2     setosa
0
source

Source: https://habr.com/ru/post/1618612/


All Articles