R rstats How to replace one character at one place in a string

I'm trying to write a function that will take a string and replace one character with another, but I want it to return every substitution of that character's replacement. I would like to replace each i with an l, but I don't want to do it globally like in gsub, and I don't want to do only the first one like in sub. I think the example best illustrates this. If I pass the name keviin (with two i's):

thisFunction("keviin")
[1] kevlin keviln kevlln

      

So I'll be back, replacing the first i, the second i, and then both i. This seems to work for recursion, but first I need to figure out how to replace only the first i. Then I can pass the resulting string to the function to get the next permutation.

Anyone have an idea to give me a boost? I tried doing this but it didn't work for me:

> substr("keviin",4,4) <- "l"
Error in substr("keviin", 4, 4) <- "l" : 
  target of assignment expands to non-language object

      

+3


source to share


3 answers


From @CarlWitthoft's idea, how about this:



thisFunction<-function(x) {
  xsplit<-strsplit(x,"")[[1]]
  ipos<-as.vector(gregexpr("i",x)[[1]])
  if (length(ipos)==1) {
    if (ipos<0) return(x) else {
      substring(x,ipos,ipos)<-"l"
      return(x)
    }
  }
  combos<-unlist(lapply(seq_along(ipos),combn,x=ipos,simplify=FALSE),recursive=FALSE)
  ret<-t(vapply(combos,function(x) {xsplit[x]<-"l";xsplit},character(length(xsplit))))
  do.call(function(...) paste(...,sep=""),as.data.frame(ret))
}

    thisFunction("keviin")
    #[1] "kevlin" "keviln" "kevlln"

      

+1


source


How about a combination of regex and fetch from a vector?

kevsplit<-unlist(strsplit('keviin',''))
the_eyes <-which( grepl('i',kevsplit))
kevsplit[sample(the_eyes,1)] <-"L"
newkev<-paste(kevsplit,collapse='')

      

This will randomly replace one of the "i" s. To change all possible permutations, do something like

for(j in 1:length(the_eyes) ) {
       calculate all permutations of the_eyes taken j at a time
       swap those selected values to kevsplit and save in some list
       }

      



I'm too lazy to write down this last bit :-)

EDIT: To clarify, other than sticking things in again, your problem is basically:

For a vector of type c (0,0,0,0,0, ....) (replacing your "i" with 0 or boolean FALSE), how many ways can you replace 1 or more values ​​with "TRUE" (or 1 )? That the standard problem in introductory combinatorics - and luckily enough computer brooms for us - turns out to be in binary!

0


source


For some reason, this works with objects, but not with pure quoted strings

thisFunction <- function(x){
+     
+     substr(x,4,4) <- 'l'
+     return(x)
+     
+ }
> thisFunction('keviin')
[1] "kevlin"

      

work.

-1


source







All Articles