Replace the character column of dataframe in R

To replace the character column of dataframe in R, we use str_replace() function of “stringr” package. Let’s see how to replace the character column of dataframe in R with an example.

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

So the dataframe will be

Replace the character column of dataframe in R 1

 

Replace the character column of dataframe in R:

  • Replace first occurrence :

str_replace() function of “stringr” package is used to replace the first occurrence of the column in R

library(stringr)
df1$replace_state = str_replace(df1$State," ","-")
df1

so the resultant dataframe will be

Replace the character column of dataframe in R 2

 

  • Replace all the occurrence :

str_replace_all() function of “stringr” package is used to replace all the occurrence of the column in R

df1$replace_state = str_replace_all(df1$State," ","-")
df1

so the resultant dataframe will be

Replace the character column of dataframe in R 3

                                                                                               

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.