title: r- Rename multiple columns by extracting part of the name
body: <p>I´m an R beginner and perhaps someone should have asked this already, but i couldn't find an answer.</p>
  
  <p>My data look like this.</p>
  
  <pre><code>id_lance &lt;-c("300_09_11", "400_09_11", "400_09_11", "400_09_11", "500_06_08",
            "500_06_08", "500_09_11", "600_06_08" , "700_09_11", "700_09_11")
  
  especie &lt;-c("esp1", "esp1", "esp1", "esp2", "esp2", "esp3", "esp2", "esp3",
          "esp3", "esp4")
  
  abundancia &lt;-as.numeric (c("190", "267","76", "111", "34", "334", "777", "1067",
                         "19", "255"))
  
  df = data.frame(id_lance, especie, abundancia)
  
  matriz &lt;-as.data.frame(tapply(df$abundancia,list(df$especie,
                                              df$id_lance),sum))
  
  matriz[] &lt;- lapply(matriz,function(x) replace(x, is.na(x), 0))
  </code></pre>
  
  <p>I want to rename columns name by extracting the first 3 numbers, i.e, "300_09_11" to "300" and so on.</p>
  
  <p>I´ve been trying out with <code>strsplit</code>and <code>gsub</code> separately and then together with no success. I don´t know if it can be done with a loop or with something like this failed attempt.</p>
  
  <pre><code>names(matriz) &lt;- gsub(strsplit(names(matriz), "_"),
                    paste0(substr(names(matriz)[[1]], 1, 3), names(matriz))) 
  </code></pre>
  
  <p>Can anyone help me out?. Thanks.</p>