replace the characters ( '-' to '/' ) in date column in R

Viewed 26

In date column , I need to change ' 04-04-2020' to ' 04/04/2020' then I need to convert to datetime.

i did it with stringr

after printing it shows all NAN.

1 Answers

Replace Specific Characters in String in R

You can try this :

1. Using gsub() function

Syntax: gsub(character,new_character, string)

print(gsub("-", "/", "04-02-2022") )

the output will be like this

enter image description here

2. Using str_replace_all() function

str_replace_all() is also a function that replaces the character with a particular character in a string. It will replace all occurrences of the character. It is available in stringr package. So, we need to install and load the package

install: install.packages("stringr")

load: library("stringr") 

Syntax: str_replace_all(string, “character”, “new_character”)

# load the stringr package
library("stringr")

print(str_replace_all("-", "/", "04-02-2022") )

#R #specificcharacter #replacestring

Related