Skip to content

Nested loop and output help

4 messages · PIKAL Petr, staysafe23

#
Hi

see inline
Use list structure for keeping such results.

lll<-list()
for(j in 1:5) {
lll[[j]] <- list()
for( i in 1:3) lll[[j]][[i]]<-rnorm(10)
}

after population of a list you can print it as a whole or only part. Here is an example with your code.

n <- seq(5,10,by=1)

lll <- vector(mode = "list", length = 10)
names(lll) <- c("mat1", "mat2", "mat3", "mat4", "cut1", "cut2", "out3a", "out3b", "out4a", "out4b")

n <- seq(5,10,by=1)

for(i in n) {
z1 <- rnorm(n,mean=400, sd=70)
z2 <- rnorm(n,mean=450, sd=90)
cor <- runif(1,min=0.4, max=0.6)
X <- z1
Y = cor*z1+(1-cor)*z2

lll[["mat1"]] <- cbind(X,Y)
dev1 <- sample(-40:40, 1, replace=T)

lll[["cut1"]] <- mean(X) + dev1
dev2 <- sample(12:54, 1, replace=T)

lll[["cut2"]] <- mean(X) + dev1 + dev2
X2 <- X-cut1
Y2 <- Y-cut2
c3 <- cor(X2,Y2)

lll[["mat2"]] <-cbind(X2,Y2)
a11 <- ifelse( X < cut1 & Y < cut2, 1, 0)
a12 <- ifelse( X < cut1 & Y >= cut2, 1, 0)
a21 <- ifelse( X >= cut1 & Y < cut2, 1, 0)
a22 <- ifelse( X >= cut1 & Y >= cut2, 1, 0)

lll[["mat3"]] <-matrix(c(sum(a11),sum(a21), sum(a12),sum(a22)), nrow = 2)
lll[["mat4"]] <-matrix(c(sum(a11),sum(a22), sum(a12),sum(a21)), nrow = 2)
lll[["out3a"]] <- mcnemar.test(mat3, correct=FALSE)
lll[["out3b"]] <- mcnemar.test(mat3, correct=TRUE)
lll[["out4a"]] <- chisq.test(mat4, correct = FALSE)
lll[["out4b"]] <- chisq.test(mat4, correct = TRUE)
}

print(lll)
do not use floating points in cycle.

better to use

for (k in 1:n) {
cc <- cor[k]
make computation with cc
}
maybe R2HTML or latex in Hmisc package can 

Regards 
Petr
1 day later
3 days later