Home > other >  Make all the the values in a data table to lower without losing the classes
Make all the the values in a data table to lower without losing the classes

Time:01-27

I would like to convert all the values in a data table without losing their class.

Example with using the iris data set

  library(datasets)
  library(dplyr)
  data(iris)

  iris <- iris %>% as.data.table()
  iris[2:3, 5] <- "SeToSa" 

  iris %>% str

  iris2 <- copy(iris)
  iris <- iris[, lapply(.SD, function(x)(tolower(x)))]

or

  iris2 <- iris2[, lapply(.SD, function(x)(ifelse(is.factor(x), tolower(x), x)))]

  iris %>% str  

However, non of these tries is able to maintain the class of each column. In addition, I am losing attributes in case they exist.

In short, is there any way that we can use lapply in a data table without losing the characteristics (class, attributes) of each column?

CodePudding user response:

Since my whole data in iris are in lower case, I have used toupper instead of tolower so that you can see what happens. Using tolower should give the expected results given the appropriate data:

lapply(iris,function(x) if(is.factor(x)) factor(toupper(x)) else(x))

please let us know if this helped.

  • Related