title: R: sum values in rows when name is the same
body: <p>I have a data frame in R where I want to sum values from rows that share a name and record the fake name for each of those rows. Can anyone think of an efficient way to do this? I wrote a for-loop (copied below), but it is extremely inefficient on the large dataset. </p>
  
  <p>Thanks in advance!</p>
  
  <p>A few things are given in this dataset: (1) no more than 2 sites will share a name and (2) the two sites will always be next in consecutive rows. I'm also open to non-R solutions, although I'm not as familiar with other frameworks. </p>
  
  <p>Example initial data:</p>
  
  <pre><code>name, fake_name, value1, value2, value3
  siteX, siteX, 4, 2, 0.5
  siteX, siteX2, 1, 4, 0.2
  siteY, siteY, 2, 1, 0.4
  siteZ, siteZ, 8, 3, 0.2
  </code></pre>
  
  <p>Transformed to: </p>
  
  <pre><code>name, value1, value2, value3, fake_name, dup_fake_name
  siteX, 5, 6, 0.7, siteX, siteX2
  siteY, 2, 1, 0.4, siteY, NA
  siteZ, 8, 3, 0.2, siteZ, NA
  </code></pre>
  
  <p>For-loop version: </p>
  
  <pre><code>data[,c(1,3:5,2)] -&gt; d2; d2$dup_fake_name &lt;- NA
  for (i in 1:(nrow(data)-1) {
    if (data$name[i] == data$name[i+1]) {
      data$value[i] &lt;- data$value[i] + data$value[i+1]
      data$dup_fake_name[i] &lt;- data$fake_name[i+1]
  }}
  </code></pre>