如何在函数中定义可选参数

时间:2019-11-22 04:42:59

标签: r function

我正在编写一个从数据框中获取一些描述性统计信息的函数。该函数采用三个参数:数据集,数字变量集,字符变量集。当在参数中同时标识了数字和字符变量时,我设法编写了函数以成功获得所需的结果。但是,当缺少这些参数之一时,我希望该函数返回一个包含两个组件的列表,其中缺少的参数为NULL。

这是我编写的代码。如果您有答案,请告诉我。

table1 <- function(dat, numvar, charvar){
  result_n <- numeric()
  result_c <- data.frame()
  #This is the original table function for numerical values
  for (i in 1:length(numvar)) {
    new_row <- c(round(mean(dat[[numvar[i]]],na.rm = T),2) ,
                 round(median(dat[[numvar[i]]],na.rm = T),2),
                 round(sd(dat[[numvar[i]]],na.rm = T),2),
                 length(dat[[numvar[i]]])-sum(is.na(dat[[numvar[i]]])),
                 sum(is.na(dat[[numvar[i]]])))
    result_n <- rbind(result_n,new_row)
  }
  rownames(result_n) <- numvar
  colnames(result_n) <- c("Mean", "Median", "SD", "N", "N_miss")
  #Thisi is the new table for char values
  for (i in 1:length(charvar)) {
    tab.dat <- as.data.frame(table(dat[charvar[i]],useNA = "ifany" ))
    a1 <- as.character(tab.dat$Var1)
    a1[3] <- "NMiss"
    one.table <- data.frame(
      Varname = c(charvar[i], rep(" ", nrow(tab.dat)-1)),
      group = a1,
      count= tab.dat$Freq)
    result_c <- rbind(result_c, one.table)
  }
  result_list <- list(numericStats = result_n, FactorStats =result_c)
  return(result_list)
}

2 个答案:

答案 0 :(得分:0)

您可以将默认值设置为函数:

table1 <- function(dat = NULL, numvar = NULL, charvar = NULL) {...

脚本可以从那里确定缺少的内容,然后从那里开始。

答案 1 :(得分:0)

这是答案:

table1 <- function(dat, numvar=NULL, charvar=NULL){
  result_n <- numeric()
  result_c <- data.frame()
  #This is the original table function for numerical values
  #I borrowed builtin function (ifmissing) from the internet
  if(!missing(numvar)) {for (i in 1:length(numvar)) {
    new_row <- c(round(mean(dat[[numvar[i]]],na.rm = T),2) ,
                 round(median(dat[[numvar[i]]],na.rm = T),2),
                 round(sd(dat[[numvar[i]]],na.rm = T),2),
                 length(dat[[numvar[i]]])-sum(is.na(dat[[numvar[i]]])),
                 sum(is.na(dat[[numvar[i]]])))
    result_n <- rbind(result_n,new_row)
  }
    rownames(result_n) <- numvar
    colnames(result_n) <- c("Mean", "Median", "SD", "N", "N_miss")}
  #Thisi is the new table for char values
  #I borrowed builtin function (ifmissing) from the internet
  if(!missing(charvar)) {for (i in 1:length(charvar)) {
    tab.dat <- as.data.frame(table(dat[charvar[i]],useNA = "ifany" ))
    a1 <- as.character(tab.dat$Var1)
    a1[3] <- "NMiss"
    one.table <- data.frame(
      Varname = c(charvar[i], rep(" ", nrow(tab.dat)-1)),
      group = a1,
      count= tab.dat$Freq)
    result_c <- rbind(result_c, one.table)
  }}
  result_list <- list(numericStats = result_n, FactorStats =result_c)
  return(result_list)
}