title: Filter only specific strings from a column in R
body: <p>I have a dataset with a column that has comma separated values. I need to parse through each value in this column and keep only specific values and delete the others.</p>
  
  <p>The code and data that I have for this is:</p>
  
  <pre><code>myDf &lt;- structure(list(GeogPreferences = structure(1:4, .Label = c("Central and East Europe, Europe, North America, West Europe, US", 
  "Europe, North America, West Europe, US", "Global, North America", 
  "Northeast, Southeast, West, US"), class = "factor")), .Names = "GeogPreferences", class = "data.frame", row.names = c(NA, 
  -4L))
  
   regionInterest &lt;- c("Americas", "North America", "US", "Northeast","Southeast","West","Midwest","Southwest")
   k&lt;-lapply(as.character(myDf$GeogPreferences),function(x) {
     z&lt;-trimws(unlist(strsplit(x,split = ",")))
     z &lt;- ifelse((z %in% regionInterest), z[z %in% regionInterest], z)
   })
   myDf$GeogPreferences&lt;-unlist(k)
  </code></pre>
  
  <p>This is the error I am getting:</p>
  
  <pre><code>Error in `$&lt;-.data.frame`(`*tmp*`, "GeogPreferences", value = c("Central and East Europe",
  : replacement has 15 rows, data has 4
  </code></pre>
  
  <p>My dataset looks like this:</p>
  
  <pre><code>    GeogPreferences
  1   Central and East Europe, Europe, North America, West Europe, US
  2   Europe, North America, West Europe, US
  3   Global, North America
  4   Northeast, Southeast, West, US
  </code></pre>
  
  <p>If the column has any on the strings from <code>regionInterest</code>, I want to keep that string, else I want to delete it.</p>
  
  <p>The output I am expecting is:</p>
  
  <pre><code>    GeogPreferences
  1   North America, US
  2   North America, US
  3   North America
  4   Northeast, Southeast, West, US
  </code></pre>
  
  <p>Can someone help me with what I am doing wrong? Thanks!</p>