Search code examples
rkablekableextra

Rename values in r kable


Let's take the iris dataset as an example.

dat <- iris[1:10, ]
dat[, 1:4] <- round(dat[ ,1:4])

As you can see, the first four columns contain numerical values and the final column contains character values.

Now, when creating a kable table, I would like to rename the values so that the first column contains character values (0 becomes "Zero", 2 becomes "Two", etc.), the second to forth columns remain the same (i.e. numerical) and the values in the final column starts with a capital letter ("Setosa"). Is it possible to achieve this using the kableExtra package? I would prefer if I didn't have to recode the values inside the data frame.


Solution

  • Here is a solution with different packages. I hope this is what you are looking for. First manipulate the data with different packages then create kable table

    library(tidyverse)
    library(kableExtra)
    library(xfun) # numbers_to_words function
    
    # your data
    dat <- iris[1:10, ]
    dat[, 1:4] <- round(dat[ ,1:4])
    
    # create kable table
    dat1 <- dat %>% 
      mutate(Sepal.Length = numbers_to_words(Sepal.Length)) %>% 
      mutate(Species = str_to_title(Species)) %>% # from stringr package in tidyverse
      kbl() %>%
      kable_styling()
    dat1 # call table
    

    enter image description here