Is there anyway I can convert a vectors objectname to a string to be used in fx: Monkey<-c(0,0,0,1,1,1) Wax<-c(1,0,1,0,1,0) f<-function(x,y){ table(x,y) } f(Monkey,Wax) so that the printout is not y x 0 1 0 1 2 1 2 1 but Wax Monkey 0 1 0 1 2 1 2 1 -- View this message in context: http://r.789695.n4.nabble.com/Using-objectname-in-function-tp2329632p2329632.html Sent from the R help mailing list archive at Nabble.com.
On Wed, Aug 18, 2010 at 12:10 PM, JesperHybel <jesperhybel at hotmail.com> wrote:> f<-function(x,y){ table(x,yIf you look at the code for 'plot', you'll see it does that with some deparse/substitute magic. Then use the dnn option to table to set the names: f<-function(x,y){ table(x,y,dnn=c(deparse(substitute(x)),deparse(substitute(y))))} Barry
On Wed, Aug 18, 2010 at 7:10 AM, JesperHybel <jesperhybel at hotmail.com> wrote:> > Is there anyway I can convert a vectors objectname to a string to be used in > fx: > > Monkey<-c(0,0,0,1,1,1) > Wax<-c(1,0,1,0,1,0) > > f<-function(x,y){ table(x,y) } > > f(Monkey,Wax) > > so that the printout is not > > ? y > x ? 0 1 > ?0 1 2 > ?1 2 1 > > but > > ? ? ? ? ?Wax > Monkey 0 1 > ? ? ? ?0 1 2 > ? ? ? ?1 2 1 >Try this: f <- function(...) eval.parent(substitute(table(...)))
On 18/08/2010 7:10 AM, JesperHybel wrote:> Is there anyway I can convert a vectors objectname to a string to be used in > fx: > > Monkey<-c(0,0,0,1,1,1) > Wax<-c(1,0,1,0,1,0) > > f<-function(x,y){ table(x,y) } > > f(Monkey,Wax) > > so that the printout is not > > y > x 0 1 > 0 1 2 > 1 2 1 > > but > > Wax > Monkey 0 1 > 0 1 2 > 1 2 1 > >deparse(substitute(x)) will give the expression that was passed as argument x in the function. Getting table() to make use of these is a little tricky. Probably the easiest way is to construct a call using do.call(): f <- function(x, y) { xname <- deparse(substitute(x)) yname <- deparse(substitute(y)) args <- list(x,y) names(args) <- c(xname, yname) do.call(table, args) } Duncan Murdoch
On Wed, Aug 18, 2010 at 7:23 AM, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:> On Wed, Aug 18, 2010 at 7:10 AM, JesperHybel <jesperhybel at hotmail.com> wrote: >> >> Is there anyway I can convert a vectors objectname to a string to be used in >> fx: >> >> Monkey<-c(0,0,0,1,1,1) >> Wax<-c(1,0,1,0,1,0) >> >> f<-function(x,y){ table(x,y) } >> >> f(Monkey,Wax) >> >> so that the printout is not >> >> ? y >> x ? 0 1 >> ?0 1 2 >> ?1 2 1 >> >> but >> >> ? ? ? ? ?Wax >> Monkey 0 1 >> ? ? ? ?0 1 2 >> ? ? ? ?1 2 1 >> > > Try this: > > ?f <- function(...) eval.parent(substitute(table(...))) >Actually this would be good enough: f <- function(...) table(...) or even f <- table