[R] R 3.1.2 using a custom function in aggregate() function on Windows 7 OS 64bit
David Winsemius
dwinsemius at comcast.net
Thu Mar 5 19:09:28 CET 2015
On Mar 4, 2015, at 2:02 PM, Typhenn Brichieri-Colombi via R-help wrote:
> Hello,
>
> I am trying to use the following custom function in an aggregatefunction, but cannot get R to recognize my data. I’ve read the help on function()and on aggregate() but am unable to solve my problem. How can I get R torecognize the data inputs for the custom function nested within aggregate()?
>
> My custom function is found below, as well as the errormessage I get when I run it on a test data set (I will be using this functionon a much larger dataset (over 600,000 rows))
>
> Thank you for your time and your help!
>
> d_rule<-function(a,x){
> i<-which(a==max(a))
> out<-ifelse(length(i)==1, x[i], min(x))
> return(out)
> }
>
> a<-c(2,2,1,4,2,5,2,3,4,4)
> x<-c(1:10)
> g<-c(1,1,2,2,3,3,4,4,5,5)
> dat<-as.data.frame(cbind(x,g))
>
> test<-aggregate(dat, by=list(g), FUN=d_rule,dat$a, dat$x)
>
> Error in dat$x : $ operator is invalid for atomic vectors
That message makes no sense to me because it suggests that the 'dat'-object was not a dataframe.
I get a different error which I think I can explain:
> test<-aggregate(dat, by=list(g), FUN=d_rule,dat$a, dat$x)
Error in FUN(X[[1L]], ...) :
unused argument (c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
The aggregate.data.frame function is I believe one by one positionally matching the x and g columns to the a-parameter of the d_rule-function and would be attempting to use dat$a (which as far as I can tell doesn't exist and would throw an error if the interpreter ever got to that step) as the match to the d_rule x-parameter, but before it does that, it tries to match dat$x to some parameter in d_rule but because both parameters already have candidate objects matched up, it fails producing the error message I see.
(It's also very bad practice to use the construction as.data.frame(cbind(x,g)). It will mangle the results if there are either factor or character variables inside the cbind().
--
David.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list