Strip Leading, Trailing spaces of column in R (remove Space)

trimws() function is used to remove or strip, leading and trailing space of the column in R.  trimws() function is used to strip leading, trailing and strip all the spaces in R  Let’s see an example on how to strip leading, trailing and all space of the column in R.

  • Strip leading space of the column in R
  • Strip trailing space of the column in R
  • Strip both leading and trailing spaces of the column in R
  • Strip all the space of the column in R

Let’s first create the dataframe.

### Create Data Frame

df1 = data.frame(State <- c(' Arizona AZ ',' Georgia GG ', '     Newyork NY','Indiana IN ','Florida FL '), Score=c(62,47,55,74,31))
df1

So the resultant dataframe will be

Strip Leading, Trailing spaces of column in R 1

 

Strip Leading Space in Column in R:

trimws() function with parameter which = c(“left”) is used to strip the leading space.

# Strip Leading Space 

df1$Left_strip <- trimws(df1$State, which = c("left"))
df1

resultant dataframe will be

Strip Leading, Trailing spaces of column in R 2

 

Strip Trailing Space in Column in R:

trimws() function with parameter which = c(“right”) is used to strip the trailing space

# Strip trailing Space 

df1$right_strip <- trimws(df1$State, which = c("right"))
df1

resultant dataframe will be

Strip Leading, Trailing spaces of column in R 3

 

Strip leading and Trailing Space in Column in R:

trimws() function with parameter which = c(“both”) is used to strip the leading and trailing space

# Strip leading and trailing Space 

df1$left_and_right <- trimws(df1$State, which = c("both"))
df1

resultant dataframe will be

Strip Leading, Trailing spaces of column in R 4

 

Strip all the Spaces in Column in R:

gsub() function is used to strip all the space of the column in below example.

# Remove all the Space 

df1$Remove_all_space <- gsub('\\s+', '', df1$State)
df1

resultant dataframe will be

Strip Leading, Trailing spaces of column in R 5

 

                                                                                                           

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.