R 循环后更新矩阵和方差
我有一个带有8X11矩阵的数组,名为results2,我正尝试以迭代方式(大约1000次)完成两件事R 循环后更新矩阵和方差,r,loops,vector,matrix,variance,R,Loops,Vector,Matrix,Variance,我有一个带有8X11矩阵的数组,名为results2,我正尝试以迭代方式(大约1000次)完成两件事 在矩阵中一次随机选择4个单元格,并向该选择中添加或减去一个值。这些值需要以(+、-、-、+)或(-、+、+、-)的方式添加。进行此加法/减法运算后,8X11矩阵应进行更新修改,并应重复此过程 每次循环后,计算并更新8X11矩阵中每个单元格的方差,并将其保存到向量中。最后应该有88个向量,其中包含一个方差值——矩阵中的每个单元格对应1个向量 到目前为止,我得到的是: r2 <- result
r2 <- results[2,,]
dat <- r2[sample(prod(dim(r2)),4)] #randomly samples from the 8X11 matrix
dat <- as.matrix(dat)
sampleRand <- function(dat) {
x_min = seq(0,min(sample(dat,4)), by=0.01) #random sampling for 4 cells and finds range from 0 to the min of that sample
x.min = sample(x_min,1) # randomly selects the min to use to add or subtract by
flip = sample(0:1,1,rep=T) #if flip is = 1 then do +,-,-,+ if flip = 0 then do -,+,+,-
if(flip > 0) {
dat[1,1] = dat[1,1] + x.min
dat[2,1] = dat[2,1] - x.min
dat[3,1] = dat[3,1] - x.min
dat[4,1] = dat[4,1] + x.min
if (dat[1,1] < 0 ||
dat[2,1] < 0 ||
dat[3,1] < 0 ||
dat[4,1] < 0)
{ print("FALSE")
}
} else if(flip == 0) {
dat[1,1] = dat[1,1] - x.min
dat[2,1] = dat[2,1] + x.min
dat[3,1] = dat[3,1] + x.min
dat[4,1] = dat[4,1] - x.min
} else if (dat[1,1] < 0 ||
dat[2,1] < 0 ||
dat[3,1] < 0 ||
dat[4,1] < 0)
{ print("FALSE")
}
}
首先,我建议编写问题,以便其他人可以在自己的控制台中生成矩阵,而无需复制和粘贴
r2 = matrix( runif(88), 8, 11 )
生成0到1之间的8 x 11随机数矩阵。接下来,您可能应该使用更多的内置函数并将代码矢量化。这将使你更容易理解你的意图。下面的代码是否与您现在所做的相同?我想可能吧。把它看完,看看它是否能做到。如果没有,那么尝试以类似的方式简化代码,以便更容易理解
r2 = matrix( runif(88), 8, 11 )
dat = sample(r2,4)
sampleRand = function(dat) {
x.min = sample( seq(0, min(dat), by=0.01), 1 )
flip = sample(c(-1,1),1)
dat = dat + flip*c(1,-1,-1,1)*x.min
if( any(dat<0) ) print("FALSE")
}
你能为我们提供一个小的实践数据集吗?什么是
结果
?此外,尽可能简化代码将有助于更快地得到答案。Kevin,我添加了一个示例。这是我能得到的最简单的。
r2 = matrix( runif(88), 8, 11 )
dat = sample(r2,4)
sampleRand = function(dat) {
x.min = sample( seq(0, min(dat), by=0.01), 1 )
flip = sample(c(-1,1),1)
dat = dat + flip*c(1,-1,-1,1)*x.min
if( any(dat<0) ) print("FALSE")
}
cells = sample(length(r2),4)
r2[ cells ] = r2[ cells ] + c(1,-1,-1,1)