您可以在函数中使用一个简单的 for 循环来做到这一点:
scan.reactions = function(df){
out.id = c()
out.nsc = c()
out.hit = c()
out.miss = c()
out.fa = c()
out.cr = c()
for(resp in unique(df[,1])){
out.id = c(out.id,resp)
seq = c('',df[df[,1]==resp,2]) ## relevant sequence of events, leading with none
out.nsc = c(out.nsc,sum(seq=="Sc"))
lseq = c(df[df[,1]==resp,2],'')
t = as.matrix(table(seq=="Sc",lseq=="resp")) ## Cross table of Sc and subsequent resp
out.hit = c(out.hit,t[2,2]) ## True/True
out.miss = c(out.miss,t[2,1])
out.fa = c(out.fa,t[1,2])
out.cr = c(out.cr,t[1,1])
}
return(data.frame("ID"=out.id,
"Nb_Sc"=out.nsc,
"hit"=out.hit,
"miss"=out.miss,
"fa"=out.fa,
"cr"=out.cr))
}
我稍微更改了您的数据,以便对 P1 有一个更正确的反应并对其进行测试:
> df = structure(list(ID = c("P1", "P1", "P1", "P1", "P1", "P1", "P1",
"P1", "P2", "P2", "P2", "P2"), trigger = c("SB", "SB", "resp",
"DH", "Sc", "resp", "Sc", "resp", "SB", "resp", "Sc", "SB")), class = "data.frame", row.names = c(NA,
-12L))
> df
ID trigger
1 P1 SB
2 P1 SB
3 P1 resp
4 P1 DH
5 P1 Sc
6 P1 resp
7 P1 Sc
8 P1 resp
9 P2 SB
10 P2 resp
11 P2 Sc
12 P2 SB
> print(scan.reactions(df))
ID Nb_Sc hit miss fa cr
1 P1 2 2 0 1 6
2 P2 1 0 1 1 3
它使用Sc 和后续resp 的交叉表,似乎产生了正确的结果。