Add Space to the column in R

Add space to the column in R is accomplished in three ways like adding space to the left ,right and on either side. In this Section we will be looking on how to

  • Add space to the left of the column in R
  • Add space to the right of the column in R
  • Add space to both left and right (on either side) of the column in R

Let’s first create the dataframe

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

df1 will be

Add space to the column in R 1

 

Add space to the left of the column in R

Str_pad function along with width argument adds space to the column. default will be left

#### Add SPACE to the left

library(stringr)
df1$State_space<-str_pad(df1$State,width=16) 
df1

so the resultant dataframe will be

Add space to the column in R 2

 

Add space to the right of the column in R

Str_pad function along with width argument and side=”right” adds space to the right side of the column.

#### Add SPACE to the right

library(stringr)
df1$State_space<-str_pad(df1$State,width=16,side="right")
df1

so the resultant dataframe will be

Add space to the column in R 3

 

Add space to both left and right of the column in R

Str_pad function along with width argument and side=”both” adds space to both the sides of the column.

#### Add SPACE to both left and right

library(stringr)
df1$State_space<-str_pad(df1$State,width=16,side="both")
df1

so the resultant dataframe will be

Add space to the column in R 4

 

                                                                                                   

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.