rsubstringsubstitution

Applying substr on a string


I want to exchange one position in a characterstring with multiple characters in a loop/apply.

I have the string: "UGCACGU" and I want: c("AGCACGU", "CGCACGU", "GGCACGU")

What I tried was the following, but it does not work.

y <- c("A", "C", "G")
sapply(y, function(i) substr("UGCACGU", start = 1, stop = 1) <- i)

Error in substr("UGCACGU", start = 1, stop = 1) <- i : 
  target of assignment expands to non-language object

After some research I came across a idea using assign, but this does not work for me.

sapply(y, function(i) assign(substr("UGCACGU", start = 1, stop = 1), i))

Solution

  • One way is to use sub to replace the first letter, i.e.

    sapply(y, function(i) sub('^[A-Z]', i, "UGCACGU"))
    
    #        A         C         G 
    #"AGCACGU" "CGCACGU" "GGCACGU"