参考 Schouwenaars (2016)
else if
学习
num_views <- 14
if (num_views > 15) {
print("You're popular!")
} else if (num_views <= 15 & num_views > 10) {
print("Your number of views is average")
} else {
print("Try to be more visible!")
}
## [1] "Your number of views is average"
Because R abandons the control flow as soon as it finds a condition that is met, you can simplify the condition for the
else if
part in the second construct tonum_views > 10
. DataCamp
注意这个地方num_views <= 15
是多余的。
另外这里的 if else 条件不是向量化的,因此需要对向量执行时,需要加 map
函数
num_views <- 10:20
if (num_views > 15) {
print("You're popular!")
} else if (num_views <= 15 & num_views > 10) {
print("Your number of views is average")
} else {
print("Try to be more visible!")
}
## Warning in if (num_views > 15) {: 条件的长度大于一,因此只能用其第一元素
## Warning in if (num_views <= 15 & num_views > 10) {: 条件的长度大于一,因此
## 只能用其第一元素
## [1] "Try to be more visible!"
suppressMessages(library(tidyverse))
map(num_views,
~if (. > 15) {
print("You're popular!")
} else if (. <= 15 & . > 10) {
print("Your number of views is average")
} else {
print("Try to be more visible!")
}
)
## [1] "Try to be more visible!"
## [1] "Your number of views is average"
## [1] "Your number of views is average"
## [1] "Your number of views is average"
## [1] "Your number of views is average"
## [1] "Your number of views is average"
## [1] "You're popular!"
## [1] "You're popular!"
## [1] "You're popular!"
## [1] "You're popular!"
## [1] "You're popular!"
## [[1]]
## [1] "Try to be more visible!"
##
## [[2]]
## [1] "Your number of views is average"
##
## [[3]]
## [1] "Your number of views is average"
##
## [[4]]
## [1] "Your number of views is average"
##
## [[5]]
## [1] "Your number of views is average"
##
## [[6]]
## [1] "Your number of views is average"
##
## [[7]]
## [1] "You're popular!"
##
## [[8]]
## [1] "You're popular!"
##
## [[9]]
## [1] "You're popular!"
##
## [[10]]
## [1] "You're popular!"
##
## [[11]]
## [1] "You're popular!"
在进行到这一步后,会考虑进行 loops 运算,如 for loops 或者 while loops,后续会介绍。