String pad to the column in R
String pad to the column in R, padding the string to the left, right, or on either side of the column can be done in three ways. We’ll look at how to do it in this lesson.
In R, add a padding string to the left of the column.
In R, add a padding string to the right of the column.
In R, pad the string to the left and right (on both sides) of the column.
Let’s start by making the dataframe.
df<-data.frame(State = c('Kerala','TN', 'AP','HYD','GOA'), Score=c(622,247,455,174,321)) df
State Score 1 Kerala 622 2 TN 247 3 AP 455 4 HYD 174 5 GOA 321
Pad String to the left of the column with the width and pad arguments in the R str_pad function pads “#” to the column. The default setting will be left.
Regression Analysis » Aim » Assumptions » Coefficients » finnstats
String pad to the left column
library(stringr) df$StateNew<-str_pad(df$State,width=12,pad="#") df
As a result, the final data frame will be
State Score StateNew 1 Kerala 622 ######Kerala 2 TN 247 ##########TN 3 AP 455 ##########AP 4 HYD 174 #########HYD 5 GOA 321 #########GOA
String pad to the right column
Pads “#” to the right side of the column in R str pad function with width and pad arguments and side=”right.”
library(stringr) df$Staterighte<-str_pad(df$State,width=12,side="right",pad="#") df
State Score StateNew Staterighte 1 Kerala 622 ######Kerala Kerala###### 2 TN 247 ##########TN TN########## 3 AP 455 ##########AP AP########## 4 HYD 174 #########HYD HYD######### 5 GOA 321 #########GOA GOA#########
String pad to the left and right column
With the width and pad arguments and side=”both,” the str pad function pads “#” to both sides of the column.
library(stringr) df$Stateboth<-str_pad(df$State,width=12,side="both",pad="#") df
State Score StateNew Staterighte Stateboth 1 Kerala 622 ######Kerala Kerala###### ###Kerala### 2 TN 247 ##########TN TN########## #####TN##### 3 AP 455 ##########AP AP########## #####AP##### 4 HYD 174 #########HYD HYD######### ####HYD##### 5 GOA 321 #########GOA GOA######### ####GOA#####