title: R - Why does sapply return lists within this dataframe when searching for values in another dataframe?
body: <p>I have the following two 2 data.frames:</p>
  
  <p><strong>df1</strong></p>
  
  <pre><code>structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1, 
  1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305, 
  4455134, 4398594), post_id_unique = c("1-NA", "1-post-1", "2-NA", 
  "2-post-2", "2-post-2", "2-post-2"), to = list(NULL, 1L, NULL, 
      2L, 2L, 2L)), .Names = c("thread_id", "course_week", "user_id", 
  "post_id_unique", "to"), row.names = c(NA, 6L), class = "data.frame")
  </code></pre>
  
  <p><strong>df2</strong></p>
  
  <pre><code>structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1, 
  1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305, 
  4455134, 4398594), post_id_unique = c("1-post-1", "1-post-1125", 
  "2-post-2", "2-post-3", "2-post-43", "2-post-54")), .Names = c("thread_id", 
  "course_week", "user_id", "post_id_unique"), row.names = c(NA, 
  6L), class = "data.frame")
  </code></pre>
  
  <p>I am trying to replace <strong>df1$to</strong> with the value in <strong>df2$user_id</strong> that matches the <strong>$post_id_unique</strong> column in both files. </p>
  
  <p>I've made the following code for it:</p>
  
  <pre><code>from &lt;- as.list(df1$post_id_unique)
  replace &lt;- function(i){if(grepl("NA",i)!=TRUE) {df2[df2$post_id_unique==i,1]}}
  df1$to &lt;- sapply(from, replace)
  </code></pre>
  
  <p>Which works almost perfectly... except that every value within <strong>df1$to</strong> is a list rather than a numeric or character vector:</p>
  
  <pre><code>'data.frame':   6 obs. of  5 variables:
   $ thread_id     : int  1 1 2 2 2 2
   $ course_week   : num  1 1 1 1 1 1
   $ user_id       : num  1237305 3001241 1237305 1237305 4455134 ...
   $ post_id_unique: chr  "1-NA" "1-post-1" "2-NA" "2-post-2" ...
   $ to            :List of 6
    ..$ : NULL
    ..$ : int 1
    ..$ : NULL
    ..$ : int 2
    ..$ : int 2
    ..$ : int 2
  </code></pre>
  
  <p>Why is my original code creating lists within the dataframe? How can I unlist them? Or avoid them to start with.</p>
  
  <p>I know this is similar to a merge(), but I am interested in doing it this way for learning and other reasons. </p>