Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In R, how can I keep the names of vector elements after applying str_replace_all?

I noticed that the function str_replace_all() removes the names of the elements in my character vector. Does anyone know how to work around this, so I get to keep the names of the elements after applying str_replace_all()?

Here is an example of the problem, where I create a vector with named elements and replace all occurances of the character "c" with an "x". You can see that I am able to access the first element of the vector with testvec["first"] before the call to str_replce_all, but not after.

> testvec <- c("first"="abc", "second"="bcd", "third"="cde")

> testvec["first"]
first 
"abc" 

> testrepl <- str_replace_all(testvec, "c", "x")
> testrepl["first"]
[1] NA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add a line where you assign names of testvec to the names of testrepl:

testrepl <- str_replace_all(testvec, "c", "x")
names(testrepl) <- names(testvec)

testrepl["first"]
# first 
# "abx" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading