Removing Whitespace From a Whole Data Frame in R

后端 未结 10 612
孤街浪徒
孤街浪徒 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:55

    A lot of the answers are older, so here in 2019 is a simple dplyr solution that will operate only on the character columns to remove trailing and leading whitespace.

    library(dplyr)
    library(stringr)
    
    data %>%
      mutate_if(is.character, str_trim)
    
    ## ===== 2020 edit for dplyr (>= 1.0.0) =====
    df %>% 
      mutate(across(where(is.character), str_trim))
    

    You can switch out the str_trim() function for other ones if you want a different flavor of whitespace removal.

    # for example, remove all spaces
    df %>% 
      mutate(across(where(is.character), str_remove_all, pattern = fixed(" ")))
    

提交回复
热议问题