Delete All Spaces in Data Frame Columns in R (Example Code)

In this R tutorial you’ll learn how to delete all blanks in data frame variables.

Example Data

df <- data.frame(col_1 = c("xa xa", "la a", "  yy y", "c d e "),  # Example data in R
                 col_2 = c("W o W", "X X", "Y Y     ", "ZZZZ ZZZ"),
                 col_3 = 1:4)
df                                                                # Display data in RStudio
#    col_1    col_2 col_3
# 1  xa xa    W o W     1
# 2   la a      X X     2
# 3   yy y Y Y          3
# 4 c d e  ZZZZ ZZZ     4

Example: Apply str_remove_all Function of stringr Package to Remove Whitespace in All Columns

install.packages("stringr")                                       # Install stringr package
library("stringr")                                                # Load stringr package
df_updated <- apply(df, 2, str_remove_all, " ")                   # str_remove_all function
df_updated                                                        # Display new data
#      col_1  col_2     col_3
# [1,] "xaxa" "WoW"     "1"  
# [2,] "laa"  "XX"      "2"  
# [3,] "yyy"  "YY"      "3"  
# [4,] "cde"  "ZZZZZZZ" "4"

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top