Apply function to unique factor levels in a dataframe
<p>New to R. I have a dataframe containing information on individuals ages, gender, and whether they slept under a bed net (lets call it mlm.Lo). I want to find the proportion of people of a certain age and gender who slept under a bed net the night before out of the total population of that age and gender and assign it as a column to another dataframe (AgeppLNNET.Lo). The issue is applying the function to all the individuals, indexed by age and gender, and getting one proportion for every unique combination of age and gender.</p>

<p>I tried writing a function and using apply</p>

<pre><code>fxppLNNET.Lo  &lt;- function(x,y){
if(mlm.Lo$Sex == "F") {
      return(sum(mlm.Lo$Age == x, mlm.Lo$LNNET == 1, na.rm = TRUE))/
         (sum(mlm.Lo$Age == x, na.rm = TRUE))
    } else(mlm.Lo$Sex = "M")
      return(sum(mlm.Lo$Age == x &amp; mlm.Lo$LNNET == 1, na.rm = TRUE))/
         (sum(mlm.Lo$Age == x, na.rm = TRUE))
    }

AgeppLNNET.Lo$ppLNNET&lt;- apply(mlm.Lo$Age, mlm.Lo$Sex, fxppLNNET.Lo)
</code></pre>

<p>But I get this error</p>

<pre><code>Error in apply(mlm.Lo$Age, mlm.Lo$Sex, fxppLNNET.Lo) : 
  dim(X) must have a positive length
</code></pre>

<p>It seems like my issue is just applying the function I wrote to each unique age/gender combination. Any help is greatly appreciated.</p>