Reputation: 73
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.
Upvotes: 0
Views: 157
Reputation: 2636
If I understand you right, you probably want this:
lm.IV2 <- function(endogen, IV=NULL, exogen, df) {
if (! is.null(IV)) {
...
}
else {
...
}
}
Upvotes: 1