How to use substr() function in R to extract a specific part of a character string?




I want to extract a specific part of a character string in R using the substr() function. Suppose if the string is like this ->


Then I want to extract the string from the third character till the last. I have to do this for a whole column. The column has same type of strings except that the part after #@ can contain any number of characters. So how to extract from third position till the end in such a string. If not substr() which other function can help?




substr(string1, 3, nchar(string1))
[1] "asdsad"

The function nchar counts the string elements for us. So nchar(x) allows us to stop at the last element.


Thank you !!! Pierre Lafortune. I am trying to remove “UTC” from a column, can you suggest that how can I do so.
[1] “2017-09-10 06:24:01 UTC” “2017-11-02 16:47:26 UTC” “2017-11-02 16:37:05 UTC” “2017-11-02 16:23:53 UTC”
[5] “2017-11-02 16:15:12 UTC” “2017-11-02 03:48:53 UTC”.
I have tried already the “substr(string1, 3, nchar(string1))” but it does not work for the values after first: the highlighted part ( “2017-09-10 06:24:01 UTC”).
Thank you


you have very likely received your resolution, but for posterity purpose… here’s one way to do this…

s1 <- c(“2017-09-10 06:24:01 UTC”, “2017-11-02 16:47:26 UTC”, “2017-11-02 16:37:05 UTC”)
s1 <- str_replace(s1, “UTC”,"")
s1 <- str_trim(s1)

[1] “2017-09-10 06:24:01” “2017-11-02 16:47:26” “2017-11-02 16:37:05”