将 3 个函数合并为一个函数

Combining 3 functions into one function

我正在尝试设置一个检查数据的函数,然后 运行使用适当的函数。

我已经尝试将 tbl1 和 tbl2 移动到 TBL.Fun。它不会 运行。

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)
}

我希望 TBL.fun 检查数据并根据该检查计算并打印正确的 table。在我把函数组合成

之后
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)
  }
}

将函数 i 运行 a dput() 与单个变量组合后。

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])

您不必在 TBL.fun1 中包含所有函数,您只需调用它们,具体取决于条件。

您还可以将条件简化为 is.vectoris.null 已经 return 个逻辑值,因此您不必测试 == TRUE

我插入了2条打印语句,所以你可以看到两个函数都被调用了。

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])