rstringr

Why does str_sub (from stringr) report an error when the string is passed to it explicitly, while it works if the string is passed as a variable?


On my computer:

str_sub("TKQTAR", 2, 2) <- "Kme1"; x

returns

Error in str_sub("TKQTAR", 2, 2) <- "Kme1" : target of assignment expands to non-language object

while if I write the same code passing the string as an argument it works.

x <- "TKQTAR"
str_sub(x, 2, 2) <- "Kme1"; x

returns "TKme1QTAR"

why is that?


Solution

  • The default operation of str_sub is getting a substring from a string, which doesn't need an existing object. It creates a result which can be assigned.

    library(stringr)
    
    str_sub("TKQTAR", 2, 2)
    [1] "K"
    

    Modifying a string with str_sub is a setter operation, which needs an existing object/variable it can operate on.

    In other words there has to be an object to modify when trying to modify a string with str_sub, only calling

    str_sub("TKQTAR", 2, 2) <- "Kme1"
    

    can't assign the modification, i.e. how would you access the modified object when there's no name, similar to length(1:3) <- 2?