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
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
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
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