所以我在涉及向量之前问了一个类似的问题,并尝试将其应用于Cbind/Rbind With Ifelse Condition所示的矩阵。
以下是我正在使用的代码:
y <- c(0,5,10,0)
n <- 9
R <- t(c(2.05, 2.05, 2.05, 2.55, 2.55, 2.55, 2.95, 2.95, 2.95))
R <- (replicate(4,R))
R <- (matrix(R, nrow=4))
R <- t(apply(R,1,sort))
mat <- t(sapply(y, function(test) pmax(seq(test, (test-n+1), -1), 0) ))
mat
P <- replicate(ncol(R),(c(6447.88,6447.88,6447.88,5000)))
EnvTest <- new.env()
EnvTest$Orig <- c(548453.5,548453.5,548453.5,500000)
FuncTest2 <- function(pp) {
EnvTest$Orig <- ifelse(R[,pp]==0|mat[,pp]!=0,EnvTest$Orig,EnvTest$Orig-(P[,pp]-EnvTest$Orig*R[,pp]/1200));
return(EnvTest$Orig);
};
Test2 <- rbind(EnvTest$Orig,do.call(rbind,lapply(1:9,FuncTest2)));
x2 <- t(Test2);
x2;
以上代码完美无缺,这就是我遇到的麻烦。
x2 <- t(sapply(y, function(x) if(x == 0) x2[,seq(1,10,2)] else x2[,seq(2,10,2)]))
产生......
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 548453.5 548453.5 548453.5 500000.0 537422.2 548453.5 548453.5 491701.3 526574.8 548453.5 548453.5 483577.3
[2,] 542942.6 548453.5 548453.5 495854.2 531892.4 548453.5 548453.5 487541.2 521245.9 548453.5 548453.5 479604.9
[3,] 542942.6 548453.5 548453.5 495854.2 531892.4 548453.5 548453.5 487541.2 521245.9 548453.5 548453.5 479604.9
[4,] 548453.5 548453.5 548453.5 500000.0 537422.2 548453.5 548453.5 491701.3 526574.8 548453.5 548453.5 483577.3
[,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 515905.7 543171.1 548453.5 475624.0 505533.7 532933.3 548453.5 467953.1
[2,] 510726.1 538058.5 548453.5 471793.3 500328.6 527795.6 548453.5 464103.5
[3,] 510726.1 538058.5 548453.5 471793.3 500328.6 527795.6 548453.5 464103.5
[4,] 515905.7 543171.1 548453.5 475624.0 505533.7 532933.3 548453.5 467953.1
这太长了,因为所需的输出是一个4 x 5矩阵,而且它的列数是4倍。在我之前提出的类似的问题是处理向量,这就是为什么我认为我的代码不起作用。 所需的输出是:
[,1] [,2] [,3] [,4] [,5]
[1,] 548453.5 537422.2 526574.8 515905.7 505533.7
[2,] 548453.5 548453.5 548453.5 538058.5 527795.6
[3,] 548453.5 548453.5 548453.5 548453.5 548453.5
[4,] 500000.0 491701.3 483577.3 475624.0 467953.1
感谢任何帮助。
更新
我开始认为这样做的方法是在创建变量“Test2”时更改一些代码。不完全确定如何改变,但这是一个想法。