Posts

Showing posts with the label global-variables

Assign a dynamic function to Global Environment in R

Image
Assign a dynamic function to Global Environment in R This question will be a simple one for some members of this forum, but I am expending a lot of time searching for an answer and I did not find any working one. Let me clarify: I have a simple function that conducts a linear regression, and the results become a variable and this variable is assigned to the global environment. Straightforward method. However, every time I run this function, the variable is replaced, what I don't want. I just want to define a specific name instead of replacing this variable. Please check out this code to understand my question: set.seed(123) ds <- data.frame(income=rnorm(1000,700,20), sex=c(0,1), age=rnorm(1000,30,10)) regress <- function(iv_string) { regression_formula <- as.formula(paste("income ~", iv_string)) results <<- lm(regression_formula, ds) plot(results) print(results) } regress("age") regress("sex") Something like that regress <-...