需要在数据集上进行多重意外事件 table

Need to make multiple contingency table on a dataset

我正在尝试从以下数据集中生成多个意外事件 table。

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

    

我想要的输出是

    timeA TimeB
PA1      7     2
LAY2    16    17

我想为每个 TIP 组合和每个底池值获得一个 table

我看到了一些方法可以使用隐含 combn 函数和 crosstable 函数的函数来实现,但是没有成功地将这些函数应用于我的数据。

关于这个问题我需要一些帮助。

帕特里克

我这样做了:

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)

结果是包含所有列联表的列表

如果你想跟踪哪个底池对应的组合,我这样做了:

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,])

如果你想通过底池值来做,我会这样做:

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))
}

在这里你得到对应于 3 个底池值的 3 个列表

我希望这是你想要的