【发布时间】:2019-07-13 05:24:02
【问题描述】:
我正在尝试设置一个检查数据然后运行相应函数的函数。
我尝试将 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])
【问题讨论】:
-
您能提供
dput()的数据吗? -
什么是 dput()?
-
如果您在用于运行
TBL.fun()的变量上使用函数dput(),我们可以重现该错误。dput()返回变量的结构,因此其他人可以将其粘贴到他们的 R 控制台上并具有完全相同的变量。
标签: r function nested-function