条件语句

R 中级

Filip Schouwenaars

DataCamp Instructor

if 语句

if(condition) {
  expr
}
x <- -3
if(x < 0) {
  print("x is a negative number")
}
"x 是负数"
R 中级

if 语句

if(condition) {
  expr
}
x <- 5
if(x < 0) {
  print("x is a negative number")
}
  • 无输出
R 中级

else 语句

if(condition) {
  expr1
} else {
  expr2
}
x <- -3
if(x < 0) {
  print("x is a negative number")
} else {
  print("x is either a positive number or zero")
}
"x 是负数"
R 中级

else 语句

if(condition) {
  expr1
} else {
  expr2
}
x <- 5
if(x < 0) {
  print("x is a negative number")
} else {
  print("x is either a positive number or zero")
}
"x 要么是正数要么是 0"
R 中级

else if 语句

if(condition1) {
  expr1
} else if(condition2) {
  expr2
} else {
  expr3
}
R 中级

else if 语句

x <- -3
if(x < 0) {
  print("x is a negative number")
} else if(x == 0) {
  print("x is zero")
} else {
  print("x is a positive number")
}
"x 是负数"
R 中级

else if 语句

x <- 0
if(x < 0) {
  print("x is a negative number")
} else if(x == 0) {
  print("x is zero")
} else {
  print("x is a positive number")
}
"x 是 0"
R 中级

else if 语句

x <- 5
if(x < 0) {
  print("x is a negative number")
} else if(x == 0) {
  print("x is zero")
} else {
  print("x is a positive number")
} 
"x 是正数"
R 中级

if、else if、else

x <- 6
if(x %% 2 == 0) {
  print("divisible by 2")
} else if(x %% 3 == 0) {
  print("divisible by 3")
} else {
  print("not divisible by 2 nor by 3...")
}
"可被 2 整除"
R 中级

Passons à la pratique !

R 中级

Preparing Video For Download...