I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.
mu contains values for y0 and y1; cinterval contains four rows:
- lower 95th CI limit for y0
- upper 95th CI limit for y0
- lower 95th CI limit for y1
- upper 95th CI limit for y1
cinterval looks like this. It can be programmed to have any number of modules:
> cinterval
module.1 module.2 module.3
y0 95LCI 2.434602 1.784056 1.751713
y0 95UCI 5.988160 6.519465 6.833455
y1 95LCI 3.778811 2.681708 2.805293
y1 95UCI 9.228941 9.716476 10.258412
mu looks like this:
y0 y1
4 8
The code I have is:
incinterval.fn <- function(cov.xy, mu, n1, dr) {
cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
y0 <- NULL # Empty vector
for (module.no in 1:ncol(cinterval)) {
y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
} # If y0 inside CI, 1, else 0
y1 <- NULL # Empty vector
for (module.no in 1:ncol(cinterval)) {
y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
} # If y1 inside CI, 1, else 0
incinterval <- rbind(y0, y1) # Combines vectors
colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
return(incinterval)
}
The result, incinterval, looks like this:
module.1 module.2 module.3
[1,] 1 1 1
[2,] 1 1 1
Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.
Aucun commentaire:
Enregistrer un commentaire