首页 > 解决方案 > 将 3 个功能组合为一个功能

问题描述

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

我试图将 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 检查数据并基于该检查计算并打印正确的表格。在我将功能组合成

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

组合函数后,我在函数上运行了一个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])

标签: rfunctionnested-function

解决方案


您不必在 中包含所有函数TBL.fun1,只需根据条件调用它们即可。

您还可以将条件简化为is.vector并且is.null已经返回逻辑值,因此您不必测试== 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])

推荐阅读