Regex R函数包含plyr--ddply():无法正确通过ddply()中的参数

Regex R函数包含plyr--ddply():无法正确通过ddply()中的参数,regex,r,parameter-passing,plyr,Regex,R,Parameter Passing,Plyr,我的资料如下: >df2 id calmonth product 1 101 01 apple 2 102 01 apple&nokia&htc 3 103 01 htc 4 104 01 apple&htc 5 104 02 nokia para=c('apple','htc',

我的资料如下:

>df2
   id     calmonth       product
1 101       01           apple
2 102       01           apple&nokia&htc
3 103       01           htc
4 104       01           apple&htc
5 104       02           nokia

para=c('apple','htc','nokia')
我想知道谁的产品包含苹果和htc、苹果和诺基亚等的ID号。 我做了一个如下的函数:

>df2
   id     calmonth       product
1 101       01           apple
2 102       01           apple&nokia&htc
3 103       01           htc
4 104       01           apple&htc
5 104       02           nokia

para=c('apple','htc','nokia')
此函数为我提供了如下完美结果:

> xandy(para[1],para[3])
  calmonth csum   coproduct
1       01    2   apple&htc
2       02    0   apple&htc
但我需要的不仅仅是苹果和htc,还有苹果和诺基亚等,所以我将苹果和htc自身更改为参数,新的可能功能如下:

看到区别了吗我已将“苹果”、“htc”更改为a、b(参数) 但这根本不是我想要的

> xandy(para[1],para[3])
eval(expr、envir、enclose)中出错:缺少参数,除此之外没有默认值:警告消息: 在grep(paste0(a,“*”,b)中,产品: 参数“pattern”的长度大于1,将只使用第一个元素


解决问题的简单方法可能是:

ddply(df2, .(calmonth), summarise, 
               apple = as.numeric(length(product == "apple")),
               apple.nokia.htc = as.numeric(length(product == "apple&nokia&htc")),
               htc = as.numeric(length(product == "htc")),
               apple.htc = as.numeric(length(product == "apple&htc"))
)

在孟晨等人的帮助下,我得到了一个直截了当的答案

xandy=function(a,b){
myStr_match=paste0(a,'.*',b)
myStr_match1=paste0(b,'.*',a)
ajoinb_match=paste0(a,'&',b)
ddply(df2,.(calmonth),function(data,myStr,myStr1,ajoinb){
summarise(data,
          csum=max(length(grep(myStr,product)),length(grep(myStr1,product))),
          coproduct=ajoinb)
  },myStr=myStr_match,myStr1=myStr_match1,ajoinb=ajoinb_match)
}

也许这不是最好的答案,但不管怎样它确实有效。

只是一个旁白:我不确定这是否是您获取数据的方式,但将苹果和htc等合并到单个产品列中是个坏主意。只创建另一个具有相同ID的行要好得多,那么所有这些聚合和操作都会容易得多。感谢您的简单解决方案。但对于更广泛的应用程序,参数化方法似乎更适合。
xandy=function(a,b){
myStr_match=paste0(a,'.*',b)
myStr_match1=paste0(b,'.*',a)
ajoinb_match=paste0(a,'&',b)
ddply(df2,.(calmonth),function(data,myStr,myStr1,ajoinb){
summarise(data,
          csum=max(length(grep(myStr,product)),length(grep(myStr1,product))),
          coproduct=ajoinb)
  },myStr=myStr_match,myStr1=myStr_match1,ajoinb=ajoinb_match)
}