title: Using the separate function within a for loop in R
body: <p>I have a dataframe of patient IDs and their various medications. Their medications are each listed in the format &quot;name,code,class,dose&quot; in one string separated by commas. Code for a sample dataframe below:</p>
  <pre><code>id &lt;- c(1,2,3)
  med1 &lt;- c(&quot;Penicillin,1,Antibiotic,5mg&quot;,&quot;Fluoxetine,5,Antidepressant,20mg&quot;,&quot;Olanzapine,9,Antipsychotic,2mg&quot;)
  med2 &lt;- c(&quot;Aspirin,4,Blood thinner,81mg&quot;,NA,&quot;Lisinopril,3,Antihypertensive,10mg&quot;)
  med3 &lt;- c(NA,NA,&quot;Amlodipine,2,Antihypertensive,5mg&quot;)
  meds &lt;- data.frame(id, med1, med2, med3)
  meds
  </code></pre>
  <p><a href="https://i.stack.imgur.com/fkV6l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fkV6l.png" alt="enter image description here" /></a></p>
  <p>However, I want to separate these out by each category, so that it would look like:</p>
  <pre><code>meds2 &lt;- meds %&gt;% separate(med1, c('med_name1', 'med_code1', &quot;med_class1&quot;, &quot;med_dose1&quot;), sep=&quot;,&quot;) %&gt;% separate(med2, c('med_name2', 'med_code2', &quot;med_class2&quot;, &quot;med_dose2&quot;), sep=&quot;,&quot;) %&gt;% separate(med3, c('med_name3', 'med_code3', &quot;med_class3&quot;, &quot;med_dose3&quot;), sep=&quot;,&quot;)
  meds2
  </code></pre>
  <p><a href="https://i.stack.imgur.com/TQgAz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TQgAz.png" alt="enter image description here" /></a></p>
  <p>I am able to do this with the code I included, but I have to manually write out the separate function for every single medication. In my actual dataset, some patients have over 100 medications, so I would not be able to do this. I tried to write a for loop using the separate function but cannot get it to work:</p>
  <pre><code>meds &lt;- for(i in 1:3){
    separate(meds2[i+1], c(paste0(&quot;med_name&quot;, i), paste0(&quot;med_code&quot;, i), paste0(&quot;med_class&quot;, i), paste0(&quot;med_dose&quot;, i), sep=&quot;,&quot;))
  }
  </code></pre>
  <p>Does anyone know where I might be going wrong or know of another approach to achieve this? Thanks so much!</p>