Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unquote dimension names

Tags:

r

The following function creates a table with the variable names as dimension names

col.table <- function(var1, var2, C=T,weights=rep(1,length(var1)), margins=TRUE,data,env=parent.frame()){ 
  require(weights); require(Hmisc)
  v1 <- deparse(substitute(var1)) 
  v2 <- deparse(substitute(var2)) 
  if(!missing(data)){
    var1 <- data[,deparse(substitute(var1))]
    var2 <- data[,deparse(substitute(var2))]
    weights <- data[,deparse(substitute(weights))]
  }


  if (C) {
    crosstab <-prop.table(xtabs(weights ~ var1 + var2,data), margin=2)

    t <- cbind(crosstab, Total=prop.table(xtabs(weights ~ var1,data=data)))
    t <- rbind(t,Total = colSums(t))
    bu<-c(deparse(substitute(v1)), deparse(substitute(v2)))

    names(dimnames(t)) <- bu
    return(round(100*t,2))

}}

Some dummy data

d<-data.frame(
  vara =c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3),
  varb = c(1,1,2,2,3,3,1,1,2,2,3,3,1,1,2),
  varc= c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
  weight= c(.5,.5,.5,.5,.5,1,1,1,1,1,2,2,2,2,2))

a<-col.table(vara,varb,data=d,weights=weight)
a

I'd like the returned object (a) to show the variable names without the quotes (just vara and varb instead of "vara" and "varb" in this case). Does anyone know how to do this? I want to remove the quotes within the function rather than outside it.

like image 792
maycobra Avatar asked Jan 15 '23 15:01

maycobra


1 Answers

You did something that you did not intend, leading to this behavior.

v1 and v2 are not function arguments (i.e., promises). They are character variables, in the function's local environment. Passing them to substitute does nothing (as they are not promises), but passing to deparse adds quote characters on each side of the value. This is the problem with your code.

First:

v1 <- deparse(substitute(var1)) 
v2 <- deparse(substitute(var2)) 

Then:

bu<-c(deparse(substitute(v1)), deparse(substitute(v2)))

Change this latter line to:

bu <- c(v1, v2)

This fixes the root of the problem, rather than masking it by removing the quote characters later.

Note the added quote characters in the following expression. This is what is going wrong with your function:

> deparse('abc')
[1] "\"abc\""
like image 148
Matthew Lundberg Avatar answered Jan 22 '23 04:01

Matthew Lundberg