0

I am using this:

OriginalData <- data.frame(lapply(OriginalData, function(x) lower(trim(x))))

remove spaces and transform characters to lowers for a whole dataframe.

Unfortunately, entries like:

  Hello world

are not transformed to:

hello world

any ideas? Thanks!

cs0815
  • 16,751
  • 45
  • 136
  • 299

2 Answers2

2

use this:

tolower(trimws("  Hello world"))
[1] "hello world"

for a list you had it right:

lapply(list("  Hello world", "  Hello world", "  Hello world"), function(x) tolower(trimws(x)))

Another solution with purrr package:

purrr::map(list("  Hello world", "  Hello world", "  Hello world"), 
       function(x) tolower(trimws(x)))

shorter call with map:

purrr::map(list("  Hello world", "  Hello world", "  Hello world"), ~tolower(trimws(.)))
RLave
  • 8,144
  • 3
  • 21
  • 37
  • why not use the shorthand notation `~` when using `purrr`? – Andre Elrico Oct 10 '18 at 15:22
  • 1
    a little less clear to me, but thanks for the suggestion, i'll include it. I'm just used to the other notation – RLave Oct 10 '18 at 15:25
  • 1
    sorry to bother you again. Why would `purrr::map` be faster than `lapply`? [REFERENCE](https://stackoverflow.com/questions/45101045/why-use-purrrmap-instead-of-lapply) – Andre Elrico Oct 10 '18 at 15:28
  • uh It seems I had it totally wrong, thank you for the reference. I can't remember where I read that it was faster. – RLave Oct 10 '18 at 15:30
1

I possibly would have used trimws as well if RLave has not been faster.

OriginalData <- data.frame( A = I(c("Hehe huhu","  Hehe huhu  ", "  Hehe Huhu")), B = I(c("Funny Lol","  Funny Lol  ", "  Funny Lol")))

OriginalData[] <- lapply(OriginalData, function(x) gsub("^\\s+|\\s+$", "" , tolower(x)))
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69