简体   繁体   中英

check Argument in a function r

I try to improve my function with checking the arguments. It seems that it doesn't work right and I have a little mistake in my code. Do you have some hints for me?

I create the following dataset:

data("mtcars")

var_IV <- c("vs" , "am" , "gear") 
var_exogen <- c("disp", "hp", "drat", "wt")

lm.IV <- function(endogen, IV, exogen, df) {
  f <- as.formula(
    paste(endogen, 
          paste(c(IV, exogen), collapse = " + "),
          sep = " ~ "))
  eval(bquote(   lm(.(f), data = df)   )) 
}

mtcars_iv <- lm.IV(endogen = "mpg", 
                IV = var_IV, 
                exogen = var_exogen, 
                df = mtcars)
mtcars_noiv <- lm.IV(endogen = "mpg", 
                  IV = "", 
                  exogen = var_exogen, 
                  df = mtcars)

To fit a model I can use all or only a part of the independ variable. When I use only one part then I need to assign this with "". For this case I modify the function a bit:

lm.IV2 <- function(endogen, IV, exogen, df) {
  if (hasArg(IV)) {
    indepVarList <- c(exogen)
  } 
  else {
    indepVarList <- c(IV, exogen)
  }
  f <- as.formula(
    paste(endogen, 
          paste(indepVarList, collapse = " + "),
          sep = " ~ "))
  eval(bquote(   lm(.(f), data = df)   )) 
}

mtcars_noiv2 <- lm.IV2(endogen = "mpg", 
                     exogen = var_exogen, 
                     df = mtcars)

But here I get the error message, that the IV Argument is missing.

If I understand you right, you probably want this:

lm.IV2 <- function(endogen, IV=NULL, exogen, df) {
  if (! is.null(IV)) {
    ...
  } 
  else {
    ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM