Search code examples
rvectorstr-replace

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

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"