title: How to create a new variable in a data frame using grep or grepl to simplify levels in a categorical variable
body: <p>I am using grep and grepl to search through a character variable and create simplified levels. </p>
  
  <p>I have tried to get the results in a dataframe. I have also tried using if and else if statements and just designating the variables. I have attached this code and the for if statement does not run.</p>
  
  <pre><code>for(i in 1:length(D$ID)){
  if(grepl("Bachelor",  D$NDEGREE)[i]){D$NDegree[i] &lt;- "Bachelors"}
  else if(grepl("BS", D$NDEGREE)[i]){D$NDegree[i] &lt;- "Bachelors"}
  else if (grepl("Master", D$NDEGREE)[i]){D$NDegree[i] &lt;- "Masters"}
  else if(grepl("Doctor", D$NDEGREE)[i]){D$NDegree[i] &lt;- "Doctors"}
  else(D$NDegree[i] &lt;- D$NDEGREE[i])}
  
  Bachelors &lt;-  D[grep("Bachelor", D$NDEGREE),]
  BS &lt;-  D[grep("BS", D$NDEGREE),]
  Masters &lt;- D[grep("Master", D$NDEGREE),]
  Doctors &lt;- D[grep("Doctor", D$NDEGREE),]
  </code></pre>
  
  <p>EDIT:  I also tried                                           </p>
  
  <pre><code>D$NDEGREE &lt;- gsub("Bachelor", "Bachelors", D$NDEGREE)
  D$NDEGREE &lt;- gsub("BS", "Bachelors", D$NDEGREE)
  D$NDEGREE &lt;- gsub("Master", "Masters", D$NDEGREE)
  D$NDEGREE &lt;- gsub("Doctor", "Doctors", D$NDEGREE)
  </code></pre>
  
  <p>This just runs through but nothing happens. 
  The for if statement doesnt work. it just keeps running indefinitely.</p>