Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a character to a string in R [duplicate]

Tags:

r

I have something like this:

text <- "abcdefg"

and I want something like this:

"abcde.fg"

how could I achieve this without assigning a new string to the vector text but instead changing the element of the vector itself? Finally, I would like to randomly insert the dot and actually not a dot but the character element of a vector.

like image 367
Ela Avatar asked Aug 01 '16 17:08

Ela


People also ask

What does duplicated do in R?

The R function duplicated() returns a logical vector where TRUE specifies which elements of a vector or data frame are duplicates.


1 Answers

We can try with sub to capture the first 5 characters as a group ((.{5})) followed by one or more characters in another capture group ((.*)) and then replace with the backreference of first group (\\1) followed by a . followed by second backreference (\\2).

sub("(.{5})(.*)", "\\1.\\2", text)
#[1] "abcde.fg"

NOTE: This solution is direct and doesn't need to paste anything together.

like image 73
akrun Avatar answered Oct 09 '22 12:10

akrun