Otis Aarts
Otis Aarts

Reputation: 1

I am using the ... in R for control variables in a function I am making, how do I convert the control variables to a list?

I have this function which does a geographically weighted regression, I have my shape-file, x for x variable and y for y variable, the ... is for the control variables. For example I want to call a regression first but with multiple control variables - how would I do that?

GWR.function <- function(shape1, x, y, ...) {
    model <- lm(shape1[[x]] ~ shape1[[y]] + shape1[[...]])
    return(summary(model))
}

I assume that it requires the use of a list but I am not sure how to do this.

Upvotes: 0

Views: 186

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226871

In general do.call() is how you introduce a list as the arguments to a function. Here I combined y with ... and passed the resulting character vector to reformulate. If you want to work with individual elements of ..., list(...) will convert it to a "regular" list.

## set up example
dd <- data.frame(x=1:10,y=rnorm(10), z=rnorm(10))

GWR.function <- function(shape1, x, y, ...) {
    predvars <- do.call("c",c(list(y),...))
    form <- reformulate(predvars, response=x)
    model <- lm(form, data=shape1)
    return(summary(model))
}
GWR.function(dd, "x","y","z")

You could redefine your function as function(shape1, x, ...) to simplify the code slightly (then predvars <- do.call("c", ...))

Upvotes: 2

Related Questions