How to convert this 'for' loop to a vector solution

This question is related to: Convert long state names embedded with other text to two-letter state abbreviations

Following for loop code works well.

for(r in 1:nrow(states.list)) { states = sub(states.list[r,1], states.list[r,2], states) } states [1] "Plano NJ" "NC" "xyz" "AL 02138" "TX" "Town IA 99999"


states <- c("Plano New Jersey", "NC", "xyz", "Alabama 02138", "Texas", "Town Iowa 99999") states.list = structure(list(state.name = structure(c(4L, 1L, 5L, 2L, 3L), .Label = c("Alabama", "Iowa", "Minnesota", "New Jersey", "Texas"), class = "factor"), state.abb = structure(c(4L, 1L, 5L, 2L, 3L), .Label = c("AL", "IA", "MN", "NJ", "TX"), class = "factor")), .Names = c("state.name", "state.abb"), class = "data.frame", row.names = c(NA, -5L)) states.list state.name state.abb 1 New Jersey NJ 2 Alabama AL 3 Texas TX 4 Iowa IA 5 Minnesota MN

I tried following to have a vector solution, but they do not work:

apply(states.list, 1, function(x) { sapply(states, function(y) { sub( x[1], x[2], y ) }) }) sapply(states, function(x) sub(states.list[,1], states.list[,2], x)) apply(states.list, 1, function(x) sub(x[1],x[2], states))

How can I convert it to a vector solution (using apply etc, without using any special packages)? Thanks for your help.

Edit: output of akrun's solution:

sapply ( seq_len(nrow(states.list)), function(i) { + sub(states.list[i,1], states.list[i,2], states[i]) + }) [1] "Plano NJ" "NC" "xyz" "Alabama 02138" "Texas"


I doubt this can be vectorized. At best you can hide the for loop under an *apply equivalent, or using Reduce like here:

ARGS <- split(states.list, seq_len(nrow(states.list))) FUN <- function(x, y) gsub(as.character(y$state.name), as.character(y$state.abb), x) Reduce(FUN, ARGS, states)

It's fancy and all but it is IMHO not worth the effort: it is probably not faster than a for loop and it is much harder to understand, isn't it? There's a little too much stigma around using for in R.


  • PHP Script for States to Abbreviations Not Working Correctly
  • Javascript regex replace using object property lookup from match is “undefined”
  • Angular 2 - Bootstrap (Ng2-Bootstrap) typeahead implementation
  • putting text on the X Axis of Graphs
  • How to set EXTJS Combobox label width
  • Can anyone help me identify the Exception in thread “AWT-EventQueue-0” java.lang.NullPointerExceptio
  • Pull to refresh in Angular Js
  • How to find the node position of a value in an XML tree?
  • Word cloud in R with two separate values
  • php move nodes to parent array
  • Failing to load properties file in an Eclipse - JUnit test
  • Google Drive: Move file to folder
  • Scrape values from HTML select/option tags in R
  • Assembly INT 13h - read disk problem
  • Cannot connect to my database from within SQL Management Studio
  • Boost:Serialization: Who cleans up the deserialized data?
  • Help me understand this C code (*(void(*) ()) scode) ()
  • ArrayList capacity size increasing strange behaviour
  • How to handle Service unavailable scenarios with Jersey REST
  • Pure JerseyTest without letting Spring messing with services
  • including a c/c++ header file in fortran subroutines
  • getting Json result in Android
  • geom_map “map_id” reference issue
  • RS-232 communication using an Arduino Duemilanove and the Cutedigi RS-232 interface
  • Jersey REST api multiple resources
  • How to parse the geolocation json from google for lng and lat in objective-c
  • Fatal error: Call to a member function fetch() on a non-object?
  • WPF auto resize elements
  • Aspect not executed in Spring
  • pure javascript dom dynamic insert, update and delete
  • jersey/tomcat Description The origin server did not find a current representation for the target res
  • Spring: No transaction manager has been configured
  • embed rChart in Markdown
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal