title: Using an IF statement to create an ordinal variable
body: <p>I'm new to R and have a question concerning a project of mine.</p>
  
  <p>I have a variable, Age.Range from an imported dataset (od) about overdoses. The variable Age.Range contains these levels:</p>
  
  <p>15-19,
  20-24,
  25-29,
  30-39,
  40-49,
  50-59,
  60-69,
  70-79</p>
  
  <p>I want to create a new, ordinal variable representative of Age.Range, such that 15-19 will be represented as 1, 20-24 will be represented 2, 25-29 will be represented as 3, and so on and so forth.</p>
  
  <p>In SAS my code would look like this:</p>
  
  <pre><code>if Age.Range="15-19" then AgeOrdinal=1;
  else if Age.Range="20-24" then AgeOrdinal=2
  
  if Age.Range="20-24" then AgeOrdinal=3;
  else if Age.Range="24-29" then AgeOrdinal=4
  
  if Age.Range="30-39" then AgeOrdinal=5;
  else if Age.Range="40-49" then AgeOrdinal=6
  
  etc.
  </code></pre>
  
  <p>Can I do a similar thing in R? If so, how? Thanks!</p>
  
  <p>P.S., I know how to create a dummy variable like </p>
  
  <pre><code>od$SurviveYes &lt;- ifelse(od$Survive=="Y", 1, 0)
  </code></pre>
  
  <p>But I would like to have a variable with more than two levels. </p>
  
  <p>So far, this is my poor attempt:</p>
  
  <pre><code>&gt; od$AgeOrdinal &lt;- c()
  &gt; age &lt;- function(od$Age.Range){
  &gt;   sapply(od$Age.Range, function(x) if(x == "15-19") 1 
  +          else if (x == "20-24") 2 
  +          else if (x == "25-29") 3
  +          else if (x == "30-39") 4
  +          else if (x == "40-49") 5
  +          else if (x == "50-59") 6
  +          else if (x == "60-69") 7
  +          else (x == "70-79") 8
  &gt; }
  </code></pre>
  
  <p>Thank you in advance!</p>