So I have asked a similar question before involving vectors and tried to just apply it a matrix as shown in Cbind/Rbind With Ifelse Condition.
Here is the code that I am working with:
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;
The above code works perfectly fine, this is what I am having trouble with.
x2 <- t(sapply(y, function(x) if(x == 0) x2[,seq(1,10,2)] else x2[,seq(2,10,2)]))
which produces...
[,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
which is too long because the desired output is a 4 x 5 matrix, and this has 4 times the number of columns. In the question that I asked before which is similar was dealing with vectors which is why I think my code does not work. The desired output is:
[,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
Any help is appreciated.
Update
I am starting to think maybe the way to do this is change some of the code when the variable "Test2" is created. Not exactly sure how to change, but it is an idea.