Recommand · June 3, 2021 0

Need to make multiple contingency table on a dataset

I am trying to make multiple contingency tables from the following dataset.

data=data.frame(TIP=c("PA1", "LAY2", "MAT1", "STU", "PA1", "LAY2", "MAT1", "STU","PA1", "LAY2", "MAT1", "STU"), timeA=c(7,16,37,8,5,13,15,28,23,17,5,16), TimeB=c(2,17,23,13,9,7,8,12,24,21,8,15), pot=c("S1","S1","S1","S1", "S2", "S2","S2", "S2", "S3", "S3","S3", "S3"))

    TIP timeA TimeB pot
1   PA1     7     2  S1
2  LAY2    16    17  S1
3  MAT1    37    23  S1
4   STU     8    13  S1
5   PA1     5     9  S2
6  LAY2    13     7  S2
7  MAT1    15     8  S2
8   STU    28    12  S2
9   PA1    23    24  S3
10 LAY2    17    21  S3
11 MAT1     5     8  S3
12  STU    16    15  S3

    

the output that I want is

    timeA TimeB
PA1      7     2
LAY2    16    17

I would like to get one table for each combination of TIP and for each pot values

I saw some way to do that with function implying the combn function and the crosstable function, but did not succeed in applying these functions to my data.

I need some help on this issue please.

Patrick

I did this:

data=data.frame(TIP=c("PA1", "LAY2", "MAT1", "STU", "PA1", "LAY2", "MAT1", "STU","PA1", "LAY2", "MAT1", "STU"), timeA=c(7,16,37,8,5,13,15,28,23,17,5,16), TimeB=c(2,17,23,13,9,7,8,12,24,21,8,15), pot=c("S1","S1","S1","S1", "S2", "S2","S2", "S2", "S3", "S3","S3", "S3"))
b = combn(1:nrow(data),2)

f = function(i){
  return(rbind(data[i[1],2:3],data[i[2],2:3]))
}
res =apply(b, 2, f)

The result is a list with all your contingency tables

if you want to track to which pot correspond the combination I’d done this:

data$new= paste(data$TIP,data$pot,sep='_')

b = combn(data$new,2)

f = function(i){
  return(rbind(data[data$new==i[1],2:3],data[data$new==i[2],2:3]))
}
res =apply(b, 2, f)
names(res)=paste(b[1,],b[2,])

if you wanna do it by pot values, I’d have done this:

for(j in unique(data$pot)){c = data[data$pot==j,]
b = combn(1:nrow(c),2)

f = function(i){
  return(rbind(c[i[1],2:3],c[i[2],2:3]))
}
assign(paste0('res', j),apply(b, 2, f))
}

Here you get 3 list corresponding to the 3 pot values

I hope it was what you wanted