Home > Net >  Apply same function to Change Letter Case of Column Names
Apply same function to Change Letter Case of Column Names

Time:01-31

I have a nested list with two data.frames, and I would like to change all variable names and variable categories to uppercase

my_list <- list(my_name = data.frame(c("Juan", "CArlos", "RRicardo")),
                my_data = data.frame(c("Lunes", "Martes", "Miercoles")))

The result I am looking for is

$MY_NAME
c..JUAN....CARLOS....RRICARDO..
1                            JUAN
2                          CARLOS
3                        RICARDO

$MY_DATA
c..LUNES....MARTES....MIERCOLES..
1                             LUNES
2                            MARTES
3                         MIERCOLES

CodePudding user response:

We can loop over the list and apply toupper on the names as well as the column values and the names of the list

setNames(lapply(my_list, \(x) {
      x[] <- lapply(x, toupper)
      names(x) <- toupper(names(x))
       x}), 
    toupper(names(my_list)))

-output

$MY_NAME
  C..JUAN....CARLOS....RRICARDO..
1                            JUAN
2                          CARLOS
3                        RRICARDO

$MY_DATA
  C..LUNES....MARTES....MIERCOLES..
1                             LUNES
2                            MARTES
3                         MIERCOLES

CodePudding user response:

We need to call toupper three times, to replace the names of the data.frames, the names of the individual data.frame columns, and the values in each column We can use the tidyverse:

library(dplyr)
library(purrr)

my_list %>%
    map(~mutate(.x, across(where(is.character), toupper)) %>% #values in each column
            rename_with(toupper)) %>% # names of the individual data.frame columns
    set_names(toupper(names(.))) #names of the data.frames

$MY_NAME
  C..JUAN....CARLOS....RRICARDO..
1                            JUAN
2                          CARLOS
3                        RRICARDO

$MY_DATA
  C..LUNES....MARTES....MIERCOLES..
1                             LUNES
2                            MARTES
3                         MIERCOLES

The where(is.character) part was added for safety. We can obviate that by substituting across(.fns=toupper) for the original call to across()

  • Related