Removing Whitespace From a Whole Data Frame in R

后端 未结 10 596
孤街浪徒
孤街浪徒 2020-12-05 03:01

I\'ve been trying to remove the white space that I have in a data frame (using R). The data frame is large (>1gb) and has multiple columns that contains whi

10条回答
  •  温柔的废话
    2020-12-05 03:58

    Picking up on Fremzy and the comment from Stamper, this is now my handy routine for cleaning up whitespace in data:

    df <- data.frame(lapply(df, trimws), stringsAsFactors = FALSE)
    

    As others have noted this changes all types to character. In my work, I first determine the types available in the original and conversions required. After trimming, I re-apply the types needed.

    If your original types are OK, apply the solution from MarkusN below https://stackoverflow.com/a/37815274/2200542

    Those working with Excel files may wish to explore the readxl package which defaults to trim_ws = TRUE when reading.

提交回复
热议问题