title: Merge, cbind: How to merge better?
body: <p>I want to merge multiple vectors to a data frame. There are two variables, <code>city</code> and <code>id</code> that are going to be used for matching vectors to data frame.</p>
  
  <pre><code>df &lt;- data.frame(array(NA, dim =c(10*50, 2)))
  names(df)&lt;-c("city", "id")
  df[,1]&lt;-rep(1:50, each=10)
  df[,2]&lt;-rep(1:10, 50)
  </code></pre>
  
  <p>I created a data frame like this. To this data frame, I want to merge 50 vectors that each corresponds to 50 cities. The problem is that each city only has 6 obs. Each city will have 4 NAs.</p>
  
  <p>To give you an example, city 1 data looks like this:</p>
  
  <pre><code>seed(1234) 
  cbind(city=1,id=sample(1:10,6),obs=rnorm(6))
  </code></pre>
  
  <p>I have 50 cities data and I want to merge them to one column in df. I have tried the following code:</p>
  
  <pre><code>for(i in 1:50){
  citydata&lt;-cbind(city=i,id=sample(1:10,6),obs=rnorm(6))   # each city data
  df&lt;-merge(df,citydata, by=c("city", "id"), all=TRUE)}    # merge to df
  </code></pre>
  
  <p>But if I run this, the loop will show warnings like this:</p>
  
  <pre><code>In merge.data.frame(df, citydata, by = c("city", "id"),  ... :
    column names ‘obs.x’, ‘obs.y’ are duplicated in the result
  </code></pre>
  
  <p>and it will create 50 columns, instead of one long column.</p>
  
  <p><strong>How can I merge <code>cbind(city=i,id=sample(1:10,6),obs=rnorm(6))</code> to <code>df</code> in a one nice and long column? It seems both <code>cbind</code> and <code>merge</code> are not ways to go.</strong></p>
  
  <hr>
  
  <p>In case there are 50 <code>citydata</code> (each has 6 rows), I can <code>rbind</code> them as one long data and use <code>data.table</code> approach or <code>expand.gird</code>+<code>merge</code> approach as <strong>Philip</strong> and <strong>Jaap</strong> suggested.</p>
  
  <p>I wonder if I can merge each citydata through a loop one by one, instead of <code>rbind</code> them and merge it to <code>df</code>.</p>