0

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?

George Sotiropoulos
  • 1,864
  • 1
  • 22
  • 32
  • 1
    if it's a factor you need to do `tolower(levels(x))` – s.brunel Aug 09 '17 at 08:08
  • 1
    Your question is not about data.table. And why you use dplyr in your question is also a mystery (you are decreasing the pool of possible answerers). You question is about `tolower`, which is documented to return class `character` vectors, and how to apply it only to the levels of factor variables. – Roland Aug 09 '17 at 08:12
  • He might have added the `dplyr` package to be able to use the `pipe operator`. One caution though. applying the `tolower` function to the levels of a factor only changes the factor levels. This will return `NA` for the new levels created. The best option is to deal with characters and changing them to factors: `factor(tolower(x))` – Onyambu Aug 09 '17 at 08:29
  • @Onyambu I see three uses of this operator here. All of them require more typing than the base R way and are completely irrelevant to the question. – Roland Aug 09 '17 at 14:03

1 Answers1

1

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.

Onyambu
  • 67,392
  • 3
  • 24
  • 53