0

This is probably a very simple question but I can't find an answer anywhere. I have a basic dataframe:

somedf <- data.frame(ageGroup = c("Under10", "Over10", "Over50", "Over100"), 
                     favColor = c("red", "pink", "purple", "blue"))

      ageGroup favColor
      1  Under10      red
      2   Over10     pink
      3   Over50   purple
      4  Over100     blue

This works:

somedf$ageGroup2 <- ifelse(somedf$ageGroup == "Under10", 1, 2 )

   ageGroup favColor ageGroup2
    1  Under10      red         1
    2   Over10     pink         2
    3   Over50   purple         2
    4  Over100     blue         2

But this doesn't:

somedf$ageGroup3 <- ifelse(somedf$ageGroup == "Under10" || 
                           somedf$ageGroup == "Over10" , 3, 4 )


   ageGroup favColor ageGroup2 ageGroup3
     1  Under10      red         1         3
     2   Over10     pink         2         3
     3   Over50   purple         2         3
     4  Over100     blue         2         3

As you can see, all of the rows take on the value that the first row receives. I thought you could do vector operations and set the values for the entire column at once with ifelse but what am I doing wrong here. Even complex / nested if/else if/else statements do the same thing.

Thanks!

Tony D
  • 184
  • 2
  • 12
  • 1
    Try with one vertical bar instead of two (i.e. `ifelse(somedf$ageGroup == "Under10" | somedf$ageGroup == "Over10" , 3, 4 )`) – Jota Feb 15 '14 at 17:36
  • From `?'||'` you can read about this difference: `The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector.` – Jota Feb 15 '14 at 17:37
  • exactly, for example `somedf$ageGroup3 <- ifelse(somedf$ageGroup == "over100" || somedf$ageGroup == "Over10" , 3, 4 )` would be all 4's because the first element of `ageGroup` is not `over10`, nor `over100`. – Usobi Feb 15 '14 at 17:42
  • See this http://stackoverflow.com/questions/21299103/if-statemtent-with-error-i-never-seen/21299159#21299159 also. – Fernando Feb 15 '14 at 18:07

0 Answers0