Q:

the difference between for loops in R and python

My function has to turn all uppercases in a given string to lowercases and vice versa. I used to solve such problems with loops. So, my code is:
mirror_case <- function(x){
   for(i in x){
     ifelse(i==toupper(i),x <- 
       str_replace_all(x,i,tolower(i)),
            ifelse(i==tolower(i),x <- 
       str_replace_all(x,i,toupper(i)),
                  x <- gsub(i,i,x)))}
   return(x)}

I checked this on several strings. Sometimes it works and sometimes doesn't.  
> d
[1] "LKJLjlei 33"
> mirror_case(d)
[1] "LKJLjlei 33"

> e
[1] "asddf"
> mirror_case(e)
[1] "ASDDF"

> f
[1] "ASDDF"
> mirror_case(f)
[1] "asddf"

So, what's wrong with this function?
I'd like not only to get the answer, but also some explanations to understand the problem and not come back here with the similar question.

A:

A string in R is not a sequence like it is in python, and can not be traversed in a for loop like this. You should break the string to individual characters first. Try this:
mirror_case <- function(s) {
  # break to characters
  chars <- strsplit(s, '') 
  # apply your ifelse statement to all characters
  mirror_chars <- sapply(chars, function(i) 
    ifelse(toupper(i) == i, tolower(i), toupper(i))) 
  # join back to a string
  mirror_s <- paste(mirror_chars, collapse = "")
  return(mirror_s)
}

mirror_case("LKJLjlei 33")
# [1] "lkjlJLEI 33"

