在R中使用全局变量和局部变量

时间:2018-05-24 16:26:27

标签: r

我是R编程的初学者,我试图创建一个for循环,如下所述,当我运行代码时,我得到了正确的输出。

然而,当我只看到mtcars $ M时,输出与我运行循环时得到的输出不同。在编码时我有什么遗漏吗?我们如何处理全局变量和局部变量?

for (i in mtcars[,1]) {
  if(i >= 15){
   M <- print("the value is greter than 15")} else {
    M <-  print("the value is not greter than 15")
    mtcars$M <- M
    }
}

1 个答案:

答案 0 :(得分:1)

您的错误来了,因为您只分配了列M,当值不大于15.因此整个列将是相同的。您必须在if-else条件之外分配值,并指定要在哪个行中保存值。如果您只使用mtcars$M <- M,它会将向量M分配给该列的所有行。

for (i in seq_along(mtcars$mpg)) {
  if(mtcars$mpg[i] >= 15){
    M <- "the value is greter than 15"
  } else {
    M <-  "the value is not greter than 15"
  }
  print(M)
  mtcars$M[i] <- M
}

mtcars$M