【发布时间】:2018-06-10 17:55:34
【问题描述】:
当使用 'a' 变量时,解释函数按我的预期输出数字 20。
linkedin <- c(16, 9, 13, 5, 2, 17, 14)
interpret <- function(num_views) {
if (num_views > 15) {
print("You're popular!")
return(num_views)
} else {
print("Try to be more visible!")
return(0)
}
}
a <- 20
interpret(a)
#[1] "You're popular!"
#[1] 20
那么为什么 for 循环不输出 15 和 0 以上的数字呢?
for (v in linkedin) {
interpret(v)
}
#[1] "You're popular!"
#[1] "Try to be more visible!"
#[1] "Try to be more visible!"
#[1] "Try to be more visible!"
#[1] "Try to be more visible!"
#[1] "You're popular!"
#[1] "Try to be more visible!"
我在 datacamp 网站而不是 R 软件上运行它,以防万一。
【问题讨论】:
-
请用正确的语言标记并删除一些空行:也许你可以摆脱滚动条
-
据我所知,上述代码按预期工作。请注意,逐行执行
interpret(a)(Ctrl + Enter) 将导致函数的输出被打印。将interpret作为source命令的一部分执行,甚至在循环内部执行,都会导致它静默返回。在你的循环中,尝试print(interpret(v))