-1

This statement should change the value of allmonths$DIVauth to either 1 or o based on a comparison of the values of $cfs and $Tess. Instead, it returns the following error and puts the value 1 in every row:

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

My statement:

if (allmonths$cfs >= allmonths$Tess) {
    allmonths$DIVauth <- 1
} else {
    allmonths$DIVauth <- 0
}
divibisan
  • 11,659
  • 11
  • 40
  • 58
ISJohnny
  • 7
  • 6
  • https://stackoverflow.com/help/mcve https://stackoverflow.com/help/how-to-ask – tjebo Jun 25 '18 at 22:40
  • also, look at the error message and work out what is wrong with your code. Debug 101 - break it down to small pieces and work out what is happening.type `allmonths$cfs >= allmonths$Tess` into your console. And so on – tjebo Jun 25 '18 at 22:44
  • You should post sample data. Possibly you should be using `ifelse` instead of `if`. More: https://stackoverflow.com/questions/17252905/else-if-vs-ifelse Something like `allmonths$DIVauth <- ifelse(allmonths$cfs >= allmonths$Tess, 1, 0)`. – Adam Smith Jun 26 '18 at 00:16

1 Answers1

1

Does this work as intended?

allmonths$DIVauth <- ifelse(allmonths$cfs >= allmonths$Tess, 1, 0)

Why does ifelse work when if fails? Quoting @karsten-w and adapting the provided sample: "The if construct only considers the first component when a vector is passed to it (and gives a warning)... The ifelse function performs the check on each component and returns a vector." else if(){} VS ifelse()

Example:

set.seed(1) # make following random data same for everyone
data <- sample(100, 5)
data

[1] 27 37 57 89 20

if(data > 50) {
    print("1st item > 50") 
} else {
    print("1st item <= 50")
}

[1] "1st item <= 50"
Warning message:
In if (data > 50) { :
the condition has length > 1 and only the first element will be use

ifelse(data > 50, "> 50", "<= 50")

[1] "<= 50" "<= 50" "> 50" "> 50" "<= 50"

Adam Smith
  • 2,584
  • 2
  • 20
  • 34