Apon Mansur
Apon Mansur

Reputation: 11

function for computing unique values is not working

I was just wondering why the following simple code for returning unique values of a variable in a data frame wouldn't work?

uu<-function(datum,group){
       k=unique(datum$group)
   return(k)
  }

matcars<-mtcars
mm<-uu(matcars,gear)

Unfortunately, mm only returns a NULL value. Any suggestion?


library(dplyr) 
##
uu <- function(datum, group) { 
  group1 <- substitute(group) 
  GR <- toString(group1) 
  k <- unique(datum[,GR]) 
  test <- filter(datum,group==k[1]) 
  return(test) 
} 
##
uu(mtcars, gear)

Upvotes: 1

Views: 479

Answers (1)

nrussell
nrussell

Reputation: 18612

I would recommend using the approach suggested by @akrun and @CathG, as this is probably the simplest and least error prone way of achieving your desired result, but if for some reason you insist on using the $ operator in your function, here is one possible way to do it:

uu <- function(datum, group) {
  group <- substitute(group)
  datum <- substitute(datum)
  unique(eval(call("$",datum,group)))
}
##
R> uu(mtcars,gear)
[1] 4 3 5
R> all.equal(unique(mtcars$gear),uu(mtcars,gear))
[1] TRUE
##
R> uu(mtcars,disp)
 [1] 160.0 108.0 258.0 360.0 225.0 146.7 140.8 167.6 275.8 472.0 460.0 440.0  78.7  75.7  71.1 120.1 318.0 304.0 350.0 400.0  79.0
[22] 120.3  95.1 351.0 145.0 301.0 121.0
R> all.equal(unique(mtcars$disp),uu(mtcars,disp))
[1] TRUE

Thanks to @akrun, here's another option for using the $ operator:

uu <- function(datum, group){ 
  args <- as.list(match.call()) 
  e1 <- eval(args$group, datum) 
  unique(e1) 
} 
##
R> uu(mtcars, gear)
[1] 4 3 5

Upvotes: 1

Related Questions