This is my dataframe:
disease <- c("high", "high", "high", "high", "low","low","low","low");
ToA <- c("P","A","P","P","A","A","A","P");
ToB <- c("P","A","A","P","A","P","A","P");
ToC <- c("P","P","A","P","A","A","A","P");
df <- data.frame(disease, ToA, ToB, ToC)
I am looking for contingency table as the image [where, row 1 = ToA, row 2 = ToB, row 3 = ToC]
high_P high_A low_P low_A
1 3 1 1 3
2 2 2 2 2
3 2 1 1 3
For each column in the dataframe, I need to calculate the frequency (count) for combination of P & high (disease col), P-low, A-high and A-low as you can see in the image above. I can do that by nrow for each column separately as below:
##count for col 2 in df
high_P=nrow(df[df$disease=="high" & df$ToA=="P", ])
high_A=nrow(df[df$disease=="high" & df$ToA=="A", ])
low_P=nrow(df[df$disease=="low" & df$ToA=="P", ])
low_A=nrow(df[df$disease=="low" & df$ToA=="A", ])
ToA_df=data.frame(high_P,high_A,low_P,low_A)
#count for col 3 in df
high_P=nrow(df[df$disease=="high" & df$ToB=="P", ])
high_A=nrow(df[df$disease=="high" & df$ToB=="A", ])
low_P=nrow(df[df$disease=="low" & df$ToB=="P", ])
low_A=nrow(df[df$disease=="low" & df$toB=="A", ])
ToB_df=data.frame(high_P,high_A,low_P,low_A)
#count for col 4 in df
high_P=nrow(df[df$disease=="high" & df$ToC=="P", ])
high_A=nrow(df[df$disease=="high" & df$ToC=="A", ])
low_P=nrow(df[df$disease=="low" & df$ToC=="P", ])
low_A=nrow(df[df$disease=="low" & df$ToC=="A", ])
ToC_df=data.frame(high_P,high_A,low_P,low_A)
Data = rbind(ToA_df,ToB_df,ToC_df)
It does what I want but I want to calculate that for each column one after another using loops, as for a big data set it would be difficult to calculate manually (col by col). Could anyone suggest/help how I can calculate the contingency table in R using loops or....as in the image?