asokol
asokol

Reputation: 129

Combining 3 functions into one function

I am trying to set up a function that checks the data then runs the appropriate function.

I have tried to move tbl1 and tbl2 into TBL.Fun. It won't run.

TBL.fun <- function (x,y){
  if(length(y)==1) tbl1(x[,y])
  else if(length(y)==2) tbl2(x[,y[1]],x[,y[2]])
  else print("Only two columns of data, kiddo!")

}

tbl1 <- function(x){
  tbl <- ftable(x)
  ptbl<- round(prop.table(tbl)*100,2)
  out <- tbl
  out[] <- paste(tbl,"(",ptbl,"%)")
  return(out)
}

tbl2 <- function(x,y){
  tbl <- ftable(x,y)
  ptbl<- round(prop.table(tbl)*100,2)
  out <- tbl
  out[] <- paste(tbl,"(",ptbl,"%)")
  return(out)
}

I want the TBL.fun to check the data and based on that check, compute and print the correct table. After I combined the functions into

TBL.fun1 <- function (x,y=NULL){
  if(is.vector(x)==T && is.null(y)==T) tbl1(x)
  else tbl2(x,y)
  tbl1 <- function(x){
    tbl <- ftable(x)
    ptbl<- round(prop.table(tbl)*100,2)
    out <- tbl
    out[] <- paste(tbl,"(",ptbl,"%)")
    return(out)
  }

  tbl2 <- function(x,y){
    tbl <- ftable(x,y)
    ptbl<- round(prop.table(tbl)*100,2)
    out <- tbl
    out[] <- paste(tbl,"(",ptbl,"%)")
    return(out)
  }
}

After combining the functions i ran a dput() on the function with a single variable.

Gender <- c("F","F","F","M","M","M")
Race <- c("Black","White","Asian","White","Black","Black")
> sam_dat <- cbind(Gender,Race)
dput(TBL.fun1(sam_dat[,1]))
function (x, y) 
{
    tbl <- ftable(x, y)
    ptbl <- round(prop.table(tbl) * 100, 2)
    out <- tbl
    out[] <- paste(tbl, "(", ptbl, "%)")
    return(out)
}
> TBL.fun1(sam_dat[,1])

Upvotes: 1

Views: 83

Answers (1)

SeGa
SeGa

Reputation: 9809

You dont have to include all functions in TBL.fun1, you just call them, depending on the condition.

You can also simplify the condition as is.vector and is.null already return logical values, so you dont have to test for == TRUE.

I inserted 2 print statements, so you can see that both functions are called.

TBL.fun1 <- function (x, y = NULL){
  if (is.vector(x) && is.null(y)) {
    print("used tbl1")
    tbl1(x) 
  } else {
    print("used tbl2")
    tbl2(x, y)
  }
}

Gender <- c("F","F","F","M","M","M")
Race <- c("Black","White","Asian","White","Black","Black")
sam_dat <- cbind(Gender,Race)

a = TBL.fun1(sam_dat[,1])
b = TBL.fun1(sam_dat[,2], sam_dat[,1])

Upvotes: 1

Related Questions