Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R局部全局变量_R_Global Variables_Local Variables - Fatal编程技术网

R局部全局变量

R局部全局变量,r,global-variables,local-variables,R,Global Variables,Local Variables,我试图在函数中更新一个全局变量(矩阵名:“conflusion.mat”) register.hit <-function(categ){ confusion.mat[categ,categ] = confusion.mat[categ,categ] + 1 } sapply(intersection.list,register.hit) register.hit在大量的谷歌搜索之后,我发现操作符这里有一个向量化的方法来实现相同的结果: confusion.mat <- s

我试图在函数中更新一个全局变量(矩阵名:“conflusion.mat”)

register.hit <-function(categ){
  confusion.mat[categ,categ] = confusion.mat[categ,categ] + 1
  }
sapply(intersection.list,register.hit)

register.hit在大量的谷歌搜索之后,我发现操作符这里有一个向量化的方法来实现相同的结果:

confusion.mat <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(3L, 3L))
confusion.mat[cbind(intersection.list, intersection.list)] <- 
  confusion.mat[cbind(intersection.list, intersection.list)] + 1
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    0

composition.mat你能举个可复制的例子吗?我似乎无法在
R
中重现问题。这是出于设计<代码>功能
不应有副作用。如果函数返回某些内容,请使用
apply
like函数。否则,请使用
for
循环。当然,可能有更好的、矢量化的解决方案,但您没有描述您实际想要实现的目标。也许这就是您的目标
diag(conflusion.mat)我想我确实提供了可复制的示例(dput数据)不要使用
我不会对

register.hit <-function(categ){
  confusion.mat[categ,categ] <<- confusion.mat[categ,categ] + 1
  }
confusion.mat <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(3L, 3L))
confusion.mat[cbind(intersection.list, intersection.list)] <- 
  confusion.mat[cbind(intersection.list, intersection.list)] + 1
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    0