rdata-cleaningjanitor

Can janitor::clean_names be used on only certain columns in a data frame?


I'm wanting to use janitor::clean_names() on only some of my column names in my data frame.

iris %>%
  janitor::clean_names()

The above cleans all column names.

I've tried using below to just clean the first 2 column names

iris %>%
  janitor::make_clean_names(1:2)

and

iris %>%
  janitor::clean_names(.[,1:2])

but had no luck.


Solution

  • This doesn't seem to be something the function itself supports, but you can write your own helper function

    clean_some_names <- function(dat, idx, ...) {
      names(dat)[idx] <- janitor::make_clean_names(names(dat)[idx], ...)
      dat
    }
    
    iris %>%
     clean_some_names(1:2) %>% 
     head()
    #   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
    # 3          4.7         3.2          1.3         0.2  setosa
    # 4          4.6         3.1          1.5         0.2  setosa
    # 5          5.0         3.6          1.4         0.2  setosa
    # 6          5.4         3.9          1.7         0.4  setosa