【问题标题】:remove spaces and transform characters to lowers for whole dataframe删除空格并将字符转换为整个数据帧的较低值
【发布时间】:2018-10-10 15:14:08
【问题描述】:

我正在使用这个:

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

为整个数据帧删除空格并将字符转换为小写。

不幸的是,条目如下:

  Hello world

不转换为:

hello world

有什么想法吗?谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    使用这个:

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

    对于list,你做对了:

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

    purrr 包的另一种解决方案:

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

    map 的通话时间较短:

    purrr::map(list("  Hello world", "  Hello world", "  Hello world"), ~tolower(trimws(.)))
    

    【讨论】:

    • 为什么在使用purrr时不使用简写符号~
    • 对我来说不太清楚,但感谢您的建议,我将其包括在内。我只是习惯了另一种表示法
    • 很抱歉再次打扰您。为什么purrr::map 会比lapply 快? REFERENCE
    • 呃,看来我完全错了,谢谢你的参考。我不记得我在哪里读到它更快。
    【解决方案2】:

    如果 RLave 没有更快的话,我可能也会使用 trimws

    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)))
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2018-05-01
      • 1970-01-01
      • 2015-11-16
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      相关资源
      最近更新 更多