不了解循环输出

时间:2018-06-10 17:55:35

标签: r loops for-loop

当使用'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软件,以防万一。

1 个答案:

答案 0 :(得分:0)

linkedin <- c(16, 9, 13, 5, 2, 17, 14)

interpret <- function(num_views) {
    if (num_views > 15) {
        print("You're popular!")
        print(num_views)
    } else {
        print("Try to be more visible!")
        print(0)
    }
}

a <- 20

interpret(a)

for (v in linkedin) {
    interpret(v)
}