title: Splitting string columns FAST in R
body: <p>I have a data frame with 107 columns and 745000 rows (much bigger than in my example).</p>
  
  <p>The case is, that I have character type columns which I want to separate, because they seem to contain some type-ish ending at the end of each sequence.</p>
  
  <p>I want to saparate these type-ending parts to new columns.</p>
  
  <p>I have made my own solution, but it seem to be far too slow for iterating through all the 745000 rows 53 times.</p>
  
  <p>So I embed my solution in the following code, with some arbitrary data:</p>
  
  <pre><code>set.seed(1)
  code_1 &lt;- paste0(round(runif(5000, 100000, 999999)), "_", round(runif(1000, 1, 15)))
  code_2 &lt;- sample(c(paste0(round(runif(10, 100000, 999999)), "_", round(runif(10, 1, 15))), NA), 5000, replace = TRUE)
  code_3 &lt;- sample(c(paste0(round(runif(3, 100000, 999999)), "_", round(runif(3, 1, 15))), NA), 5000, replace = TRUE)
  code_4 &lt;- sample(c(paste0(round(runif(1, 100000, 999999)), "_", round(runif(1, 1, 15))), NA), 5000, replace = TRUE)
  
  code_type_1 &lt;- rep(NA, 5000)
  code_type_2 &lt;- rep(NA, 5000)
  code_type_3 &lt;- rep(NA, 5000)
  code_type_4 &lt;- rep(NA, 5000)
  
  df &lt;- data.frame(cbind(code_1, 
                         code_2, 
                         code_3, 
                         code_4, 
                         code_type_1, 
                         code_type_2, 
                         code_type_3, 
                         code_type_4), 
                   stringsAsFactors = FALSE)
  
  df_new &lt;- data.frame(code_1 = character(),
                       code_2 = character(),
                       code_3 = character(),
                       code_4 = character(),
                       code_type_1 = character(),
                       code_type_2 = character(),
                       code_type_3 = character(),
                       code_type_4 = character(),
                       stringsAsFactors = FALSE)
  
  for (i in 1:4) {
    i_t &lt;- i + 4
    temp &lt;- strsplit(df[, c(i)], "[_]")
    for (j in 1:nrow(df)) {
      df_new[c(j), c(i)] &lt;- unlist(temp[j])[1]
      df_new[c(j), c(i_t)] &lt;- ifelse(is.na(unlist(temp[j])[1]), NA, unlist(temp[j])[2])
    }
    print(i)
  }
  
  for (i in 1:8) {
   df_new[, c(i)] &lt;- factor(df_new[, c(i)])
  }
  </code></pre>
  
  <p>Do anyone have some ideas how to speed things up here?</p>