\begin{Schunk}
\begin{Sinput}
 ## Keep cities safe, write on a copy cities2
 cities2 <- cities
 ## Method 1
 ## Puts the target match correction into the for loop
 for(i in state.abb) {
      ## target is a string, only has one element
      target <- paste0(state.name[i], "$") 
      cities2 <- gsub(target, i, cities2)
  } 
 ## Appears correct:
 cities2
\end{Sinput}
\begin{Soutput}
 [1] "Dallas TX"                "Denver CO"                "Austin TX"               
 [4] "Salem OR"                 "Salem MA"                 "California PA"           
 [7] "Long Beach CA"            "San Francisco CA"         "Texas MO"                
[10] "Nevada MO"                "St. Louis MO"             "Truth or Consequences NM"
[13] "Charleston SC"            "Charleston NC"           
\end{Soutput}
\begin{Sinput}
 ##
 ## Here is method 2. We start over,
 ## Creating a target VECTOR before the for loop.
 ## After this, target is a vector of corrected matches
 cities2 <- cities
 target <- paste0(state.name, "$") 
 ## names were lost, so re-apply them
 names(target) <- names(state.name)
 ## inspect
 head(target, 5)
\end{Sinput}
\begin{Soutput}
           AL            AK            AZ            AR            CA 
   "Alabama$"     "Alaska$"    "Arizona$"   "Arkansas$" "California$" 
\end{Soutput}
\begin{Sinput}
 for(i in state.abb) {
      ## target is a vector, choose the i'th one
      cities2 <- gsub(target[i], i, cities2)
  } 
 cities2
\end{Sinput}
\begin{Soutput}
 [1] "Dallas TX"                "Denver CO"                "Austin TX"               
 [4] "Salem OR"                 "Salem MA"                 "California PA"           
 [7] "Long Beach CA"            "San Francisco CA"         "Texas MO"                
[10] "Nevada MO"                "St. Louis MO"             "Truth or Consequences NM"
[13] "Charleston SC"            "Charleston NC"           
\end{Soutput}
\end{Schunk}
