Using for loop for iterations
The most convenient way to perform iterative operation in R is the use of a for
loop. Suppose you are given a dataset with five variables representing five different diseases for 10 people. All your variables are binary. Your task is to calculate the frequency of each variable as well as the cross-frequency of all pair-wise variables. Using a for
loop, you can easily complete this task. In this recipe, you will implement a for
loop to calculate the disease frequency and the frequency of all pair-wise variables.
Getting ready
Let’s consider you are given the following dataset mat
:
set.seed(1234) mat<-matrix(sample(c(0,1),50,replace = T),nrow = 10,ncol=5) rownames(mat) <- paste("patient", paste(1:10),sep="") colnames(mat) <- c("diabetes", "hypertension", "asthma", "jointPain", "fever") > mat diabetes hypertension asthma jointPain fever patient1 0 1 0 0 1 patient2 ...