if - εντολές διακλάδωσης

Το βίντεο έχει διάρκεια 40:25. Πιθανά να χρειάζεται λίγος χρόνος για την προβολή του.


R; rstats; if; else; ifelse
## http://stavrakoudis.econ.uoi.gr/stavrakoudis/?iid=988
## https://www.youtube.com/watch?v=vKFz2s6QYyQ

# logical expression
10 > 5

# if function, do something if expression is TRUE
if(10 > 5) 
  print("yes, it is bigger")

# Curly braces, not necessary with just one command, but always recommended
if(10 > 5) {
  print("yes, it is bigger")
}

# Curly braces, always necessary with more than one command
if(10 > 5) {
  print("yes, it is bigger") 
  print("for sure")
}

# Conditional assignment of a variable
x <- 10
if(x > 5) {
  a <- 1
}
a

# else : do something if conditions is not TRUE
if(x < 5) {
  a <- 1
} else {
  a <- 0
}
a

# Conditional assignment of a variable, check if NA
x <- NA
if(is.na(x) == TRUE) {
  a <- 1
}
a

# Conditional assignment of a variable, check if exists
y <- 10
if(exists("y") == TRUE) {
  a <- 1
} else {
  a <- 0
}
a

# Combine two rules, with AND or OR
x <- 10
y <- -2

if(x > 0 & y > 0) {
  print("both positives")
}

if(x > 0 & y > 0) {
  print("both positives")
} else {
  print("No, they are not both positives")
}

x <- 10; y <- -2
# & AND operator
if(x > 0 & y > 0) {
  print("both positives")
} else if (x < 0 & y < 0) {
  print("both negatives")
} else {
  print("one positive, one negative")
}

x <- -10; y <- -2
# | OR operator
if(x > 0 | y > 0) {
  print("at least one is positive")
} else {
  print("no one is positive")
}


# Nested if structures
x <- 10
y <- 0
if(x == 0) {
  if(y == 0) {
    print("both are zero")
  } else {
    print("first is zero, second is not")
  }
} else {
  if(y == 0) {
    print("first is not zero, second is zero")
  } else {
    print("both are not zero")
  }
}

# ifelse assignment, similar to MS EXCEL
x <- 10
ifelse(x > 0, 1, -1)
y <- ifelse(x > 0, 1, -1)
y

# It works for vectors as well
x <- c(-6, 5, 0, 3, 1)
y <- ifelse(x > 0, 1, -1)
y

# Attention, how to check results sensitive to machine precision
1 == 0.999999
all.equal(1, 0.999999)
.Machine$double.eps

# Here we expect two numbers to be equal if they differ to sixth digit
all.equal(1, 0.999999, tolerance = 1e-5)

all.equal(0, 0.0000001, tolerance = 1e-5)
abs(0 - 0.0000001) > 1e-5

if(all.equal(1, 0.999999, tolerance = 1e-5) == TRUE) {
  print("equal numbers")
}

Συνδεθείτε για περισσότερες δυνατότητες αλληλεπίδρασης,
σχολιασμοί, εξωτερικοί σύνδεσμοι, βοήθεια, ψηφοφορίες, αρχεία, κτλ.

Creative Commons License
Εκπαιδευτικό υλικό από τον Αθανάσιο Σταυρακούδη σας παρέχετε κάτω από την άδεια Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.
Σας παρακαλώ να ενημερωθείτε για κάποιους επιπλέον περιορισμούς
http://stavrakoudis.econ.uoi.gr/stavrakoudis/?iid=401.