r - 将 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])
解决方案
您不必在 中包含所有函数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])
推荐阅读
- wix - WIX Installer Preserve config file On major upgrade early Scheduling
- audio - 在将 OGG 音频转换为 MP3 时,FFMPEG 在文件开头添加了额外的内容
- r - 如果任何行包含子字符串,则标记
- java - 在 Android 上使用 cache2k 时出现 java.lang.NoClassDefFoundError
- python-3.x - 如何将极坐标图划分为 12 个分区?
- typescript - 处理 Firebase 范围查询响应
- ruby-on-rails - 使用 Rails 和 Vue.JS 将设计用户 ID 传递给 Post 模型
- angular - Angular 如何使用其对象引用删除组件实例
- sas - 在SAS中如何打印领先和落后的观察
- php - 在laravel中将数据库表导出到EXCEL