-1

I have a table where I have a numerical column of whole positive and negative values. I am trying to run a simple if statement where if the value of Yds is less than 10, then a brand new numerical column (Ydsle10) gets a 1 else a 0

Here is my code:

Data$Ydslt10 <- if(Data$Yds < 10) {Data$Ydslt10 <- 1} else {Data$Ydslt10<-0}

Here is the error:

 the condition has length > 1 and only the first element will be used

str of my table is:

 $ Name      : Factor w/ 206 levels "A.Abdullah","A.Boldin",..: 68 199 79 120 120 79 68 27 68 150 ...
 $ Team      : Factor w/ 31 levels "ARI","BAL","BUF",..: 9 9 9 4 4 9 9 9 9 4 ...
 $ Position  : Factor w/ 3 levels "RB","TE","WR": 3 2 3 3 3 3 3 1 3 1 ...
 $ Yds       : num  0 10 4 17 14 14 7 2 6 -3 ...
 $ Receptions: num  1 1 1 1 1 1 1 1 1 1 ...
 $ Targets   : num  1 1 1 1 1 1 1 1 1 1 ...
 $ Ydslt10   : num  1 1 1 1 1 1 1 1 1 1 ...
 $ Ydsgt10   : num  0 0 0 0 0 0 0 0 0 0 ...

I cannot seem to figure out the error, and web searches have not been too helpful.

lmo
  • 37,904
  • 9
  • 56
  • 69
CooperBuckeye05
  • 149
  • 2
  • 14
  • 1
    Did you really do a search on "the condition has length > 1 and only the first element will be used"? So has a ton of questions and answers. – IRTFM Feb 21 '17 at 23:57
  • Second result on Google for me - http://stackoverflow.com/questions/14170778/interpreting-condition-has-length-1-warning-from-if-function – thelatemail Feb 22 '17 at 01:07
  • Honestly, this is also a fault of the reviewers who OK'd this question instead of flagging it as a duplicate. But yes, it is generally advisable to follow these guidelines when posting a question: http://stackoverflow.com/help/how-to-ask – Artem Sokolov Feb 22 '17 at 05:55

1 Answers1

3

As the error (which is really a warning) suggests, if uses only the first element of a vector for its condition. Take a look at ifelse, which operates directly on vectors and is more appropriate for your task:

Data$Ydslt10 <- ifelse( Data$Yds < 10, 1, 0 )
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74