【问题标题】:Conditional application of a function with more than one argument (R)具有多个参数 (R) 的函数的条件应用
【发布时间】:2012-03-24 07:33:27
【问题描述】:

我正在尝试针对多个因素的每种组合将函数应用于数据集。该函数有两个参数。我尝试了基于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) 表示为事件总数的比例,对于组因素的每个组合,即@987654324 @。

我尝试编写一个函数来进行此计算,然后使用 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

我使用sapplyddply 也同样不成功。

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

【问题讨论】:

  • 坚持 Joran 的回答,但我认为您的错误消息是由于放错了 ")" 。试试by(dat,list(g1,g2),propFun(events=x ,response=y) ) 看看你的代码能不能运行。
  • 谢谢卡尔,但我相信我也尝试过那个迭代。这会产生错误Error in FUN(X[[1L]], ...) : could not find function "FUN"。根据?by,在对by 的调用中,应在附加逗号后提供进一步的FUN 参数;我无法让它工作。

标签: r conditional-statements


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-10-13
    • 2013-08-02
    • 2020-12-04
    • 2015-04-25
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多