String pad to the column in R

String pad to the column in R is accomplished in three ways like padding string to the left ,right and on either side. In this tutorial we will be looking on how to

  • Pad string to the left of the column in R
  • Pad string to the right of the column in R
  • Pad string 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

String pad to the column in R 1

 

Pad String to the left of the column in R

str_pad function along with width and pad argument pads “#” to the column. default will be left

#### pad string to the left

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

So the resultant dataframe will be

String pad to the column in R 2

 

Pad String to the right of the column in R

str_pad function along with width and pad argument and side=”right”, pads “#” to the right side of the column.

#### pad string to the right

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

So the resultant dataframe will be

String pad to the column in R 3

 

Pad string to both left and right of the column in R

str_pad function along with width and pad argument and side=”both”, pads “#” to both the sides of the column.

#### pad string to both left and right

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

So the resultant dataframe will be

String pad to the column in R 4

String pad to the column in R - image previous-small-11-1 on http://www.datasciencemadesimple.com                                                                                                   String pad to the column in R - image next_small-11-1 on http://www.datasciencemadesimple.com