有条件地应用具有多个参数的函数(R)

时间:2012-03-06 19:06:25

标签: r conditional-statements

我正在尝试将函数应用于多个因子的每个组合的数据集。该函数有两个参数。我尝试了基于previous questions on conditional summing in R的解决方案,并使用了plyr包,结果不成功。

一个例子很有用。这里,x指的是两个条件的“事件”和y到“响应”。

dat <- data.frame(x=c(0,0,1,1,0,0,1,1),
              y=c(2,1,1,2,1,2,1,0),
              g1=c("a","a","a","a","b","b","b","b"),
              g2=c("c","d","c","d","c","d","c","d"))

attach(dat)

我可以得到计数或总和等等:

numberTrials <- aggregate(y,list(g1,g2),length)
nEvents <- aggregate(x,list(g1,g2),sum)

现在我想表示事件总数(x == 1)的“2”响应数(y == 2),作为事件总数的一部分,对于组因子的每个组合,即{{ 1}}。

我尝试编写一个函数来执行此计算,然后使用length(y[x==1 & y==2])/sum(x)将函数应用于每个子集:

by

但是,对propFun <- function(events,response){ # where x is the events and y is the response nEvents <- sum(events) nResp2ToEvent <- length(response[events==1 & response==2]) propFAs <- nResp2ToEvent/nEvents return(propFAs) } dataProp <- by(dat,list(g1,g2),propFun(events=x),response=y) 的调用会产生:

by

我使用Error in propFun(events = x) : argument "response" is missing, with no default sapply同样失败了。

我确信我得到的错误有一个简单的语法修复;但是我也会对整体问题的任何更好的解决方案感兴趣。感谢

1 个答案:

答案 0 :(得分:1)

我认为这就是您所使用的ddplysummarise

ddply(dat,.(g1,g2),summarise,ev = length(y[x==1 & y==2])/sum(x))

  g1 g2 ev
1  a  c  0
2  a  d  1
3  b  c  0
4  b  d  0