0

Why following simple function does not work and gives an error:

mytestfn = function(values, groups=NULL){
    if(groups==NULL) groups = rep(1,length(values))
    aggregate(values~groups, FUN=mean)
}

vnum1 = rnorm(50)
vnum1
[1] -1.01993166 -0.41735261  0.18180007  0.25574158  0.80571197  1.89661218  0.49261977  0.40043375  0.30155048 -0.65099065
[11]  2.05399702 -2.45479400 -0.28242676 -0.03518524 -2.38285117  0.40051810 -0.24484214  1.59843096 -1.85081671 -0.67585775
[21]  1.32475440 -0.04664591 -0.74631952 -1.14186008  0.34651340  0.16898481 -1.11109084  0.26670201  0.42497016  0.55923406
[31] -0.45701506  1.27278228 -0.55062181  2.40622163 -1.45701143 -0.38779811  0.46210855 -0.06971534  0.15957646 -1.18754281
[41] -0.75757569  0.53710075 -1.09645200  0.68997692  0.10765275 -1.17708938  2.17039682 -2.55682864  0.43079839 -1.69008127

mytestfn(vnum1)
Error in if (groups == NULL) groups = rep(1, length(values)) : 
  argument is of length zero

while following statement works:

aggregate(vnum1~rep(1,length(vnum1)), FUN=mean)
  rep(1, length(vnum1))       vnum1
1                     1 -0.09467015

How can I correct this problem. Thanks for your help.

etr
  • 1,252
  • 2
  • 8
  • 15
rnso
  • 23,686
  • 25
  • 112
  • 234

1 Answers1

0
myTestFun <- function(values,groups=NULL){
  if(is.null(groups)) groups = rep(1,length(values))
  aggregate(values~groups, FUN=mean)
}
##
> myTestFun(vnum1)
  groups   values
1      1 -0.12771
nrussell
  • 18,382
  • 4
  • 47
  • 60