在函数体的同一参数中使用大于和小于

  • 本文关键字:大于 小于 参数 函数体 r
  • 更新时间 :
  • 英文 :

my_function <- function(x){
if (x > 10) {
print("Higher than 10")
} else if (x > 5 & x < 10) {
print("Between 5 and 10")
} else if (x < 5) {
print("Less than 5")
} 
}

我想创建一个函数,当我输入一个值时,它会打印一些文本。";高于10〃;以及";小于5〃;零件工作,但";介于5和10〃之间;位无法打印。我在那场争论中做错了什么?

正确的函数是:

my_function <- function(x){
if (x > 10) {
print("Higher than 10")
} else if (x > 5) {
print("Between 5 and 10")
} else if (x < 5){
print("Less than 5")
} 
}

一种更紧凑的方法是使用case_when和只有一个打印语句:

my_function <- function(x){
res <- case_when(x > 10 ~ "Higher than 10",
x > 5 & x < 10 ~ "Between 5 and 10",
x < 5 ~ "Less than 5", 
TRUE ~ "Number is 5 or 10")
print(res)
}

注意,当时,当数字不在案例中的任何范围内时,我使用了第四个条件

请注意,您的函数可以写得更好。对于if_else语句,它应该始终以else语句结束,而不是以if-else语句结束。

如下所示,当我们输入从1到10的10个值时,它只打印出8条语句,而不是10条。这是因为函数没有值5和10的打印输出。

my_function <- function(x){
if (x > 10) {
print("Higher than 10")
} else if (x > 5 & x < 10) {
print("Between 5 and 10")
} else if (x < 5) {
print("Less than 5")
} 
}
for(i in 1:10) {
my_function(i)
}
[1] "Less than 5"
[1] "Less than 5"
[1] "Less than 5"
[1] "Less than 5"
[1] "Between 5 and 10"
[1] "Between 5 and 10"
[1] "Between 5 and 10"
[1] "Between 5 and 10"

编写函数的更好方法是

my_function2 <- function(x){
if (x >= 10) {
print("Greater or Equal than 10")
} else if (x > 5 & x < 10) {
print("Between 5 and 10")
} else {
print("Less than or equal to 5")
} 
}
for(i in 1:10) {
my_function2(i)
}
[1] "Less than or equal to 5"
[1] "Less than or equal to 5"
[1] "Less than or equal to 5"
[1] "Less than or equal to 5"
[1] "Less than or equal to 5"
[1] "Between 5 and 10"
[1] "Between 5 and 10"
[1] "Between 5 and 10"
[1] "Between 5 and 10"
[1] "Greater or Equal than 10"

最新更新