如果该类别没有值,如何使用循环将 0 添加到该类别?

How to use loop to add 0 to one category if there is no values for this category?

我有两个数据集要比较,我写了一个函数来比较它们

人口数据集如下:

                  yes     no     NA
diease or not      1       9      20

但是,示例数据集可能缺少一个类别,例如:

                       no     NA
diease or not          2      7

我写了一个函数来尝试比较两个数据集并将它们应用到我拥有的整个数据框中,我写的函数如下:

tablFun6 <- function(x){
  tbl6 <- table(x,exclude=NULL)
  res6 <- c(as.vector(round(tbl6,0)),paste0(as.vector(round(prop.table(tbl6)*100,2)),"%"))
  names(res6) <- c("Yes","No","NA","Yes_Perc","No_Perc","NA_Perc")
  res6
}

并将其应用于人口数据集和样本数据集中的变量,

dis_popu <- do.call(rbind,lapply(popu[c(154,159,161:166)], 
tablFun6))
dis_samp <- do.call(rbind,lapply(samp[c(154,159,161:166)], 
tablFun6))  

但错误总是发生:

  Error in names(res6) <- c("Yes", "No", "NA", "Yes_Perc","No_Perc", 
  "NA_Perc") : 'names' attribute [6] must be the same length as the 
  vector [4]

我知道这是因为我在示例数据集中缺少一个类别,而且我分配的名称长度与 "table" 结果不匹配,但我对如何改进我的代码非常困惑。

我非常感谢任何帮助帮助我提高学习效率的帮助。谢谢!

此解决方案不使用循环,所以如果您真的想要,请告诉我,我会删除我的回复。我想你会发现这样效率更高。

告诉 R disease_or_not 是一个因素,并明确列出所有可能的水平。

> disease_or_not <- factor(c(rep('yes', 5)))
> table(disease_or_not)
disease_or_not
yes 
  5 
> disease_or_not <- factor(c(rep('yes', 5)), levels = c('no', 'yes')) # give the levels directly
> table(disease_or_not) # even though no one has 'no', R puts it in the table
disease_or_not
 no yes 
  0   5