在for循环中构造R中的函数

时间:2014-02-23 19:35:06

标签: r function for-loop

我一直在解决我的代码问题,但我被困了。我试图在R中的for循环中重复运行一个函数,同时附加到一个向量。我的代码如下:

densities = rep(NA, length(seq(0, 1, by = 0.01)))
count = 1

for (t in seq(0, 1, by = 0.01)) {
  applyThreshold(t, densities, count)
}

applyThreshold = function(t, densities, count){
  tMatrix = corMatrix
  tMatrix[corMatrix < t] = 0 
  tMatrix[corMatrix >= t] = 1
  nVector = c()
  for (n in 1:dim(tMatrix)[1]){
    nSum = sum(tMatrix[,n])
    if (nSum == 0){
      nVector = c(nVector, n)
    }
  }
  if (length(nVector) >0){
    tMatrix = tMatrix[,-(nVector)]
    tMatrix = tMatrix[-(nVector),] 
  }

  E = sum(tMatrix)/2
  V = dim(tMatrix)[1]
  densities[count] = 2*E/(V*(V-1))
  count = count + 1
}

但是,在运行此命令结束时,我的密度和计数尚未更新。我有一种感觉这是一个简单的修复,但我一直在查看R中函数的文档,但仍然卡住了。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

这种各种搞砸了。目前,您的函数返回count + 1。就是这样。您需要了解不同变量的范围。函数中的所有变量仅在调用该函数时存在于该函数中。您需要使用return()从中获取实际值并将它们存储在单独的变量中。此外,您需要确保在尝试使用它之前创建了您的功能。如果按原样运行代码,则甚至不会在for循环中创建applyThreshold。

尝试在创建函数后运行此函数以查看我的意思:

y <- applyThreshold(.5, densities, 5)
print(y)

变量corMatrix甚至不存在于您的函数中。

相关问题