R函数包含plyr--ddply():ddply()中的参数不能正确过去 [英] R function contain plyr--ddply(): parameters in ddply() cannot be past correctly
问题描述
我的数据如下:
>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')
我想获取产品中包含apple&htc,apple&nokia
等的ID的数量.
我的功能如下:
I wanna get the number of ids who's product contain apple&htc,apple&nokia
,etc.
I make a function as follows:
xandy=function(a,b){
ddply(df2,.(calmonth),summarise,
csum=length(grep(paste0('apple','.*','htc'),product)),
coproduct=paste0('apple','&','htc')
)
}
此功能可以给我带来如下完美效果:
> xandy(para[1],para[3])
calmonth csum coproduct
1 01 2 apple&htc
2 02 0 apple&htc
但是我不仅需要apple&htc
,还需要apple&nokia
等,所以我将apple and htc
自己更改为参数,新的可能的功能是这样的:
But What i need are not only apple&htc
,butapple&nokia
etc,so I alter apple and htc
themselves to parameters,new likely function like this:
xandy=function(a,b){
ddply(df2,.(calmonth),summarise,
csum=length(grep(paste0(a,'.*',b),product)),
coproduct=paste0(a,'&',b)
)
}
看到差异了吗? 我已将'apple','htc'更改为a,b(参数) 但这根本不是我想要的.
See the differences? I have altered 'apple' ,'htc' to a,b(parameters) But it is not at all what I want.
> xandy(para[1],para[3])
eval(expr,envir,enclos)中的错误:缺少参数,没有默认值另外:警告消息: 在grep(paste0(a,.*",b),product)中: 参数'pattern'的长度> 1,并且仅使用第一个元素
Error in eval(expr, envir, enclos) : argument is missing, with no default In addition: Warning message: In grep(paste0(a, ".*", b), product) : argument 'pattern' has length > 1 and only the first element will be used
推荐答案
在MengChen和其他人的帮助下,我得到了一个简单的答案.
With the help of MengChen and others, I get a straightforward answer.
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)
}
也许这不是最好的答案,但是它确实可以工作.
Maybe this is not the best answer, but it does work anyway.
这篇关于R函数包含plyr--ddply():ddply()中的参数不能正确过去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!