Brian
Brian

Reputation: 163

R does NOT recognize a parameter when writing a function

I'm currently trying to write my own function that will generate a few graphs by determining a variable. But for some reason, R isn't too happy with the following code.

explore = function(var, title) {
  par(mfrow=c(1,2))
  tr = rpart(y ~ {{var}}, data = df)
  plot(tr, margin = .1, uniform = TRUE, main = title)
  text(tr, fancy = TRUE, use.n = TRUE)
  stripchart({{var}} ~ y, main = title, data = df, method = "stack")
  boxplot({{var}} ~ y, data = df)
}

The output states that the "var" cannot be found from the df. Any help/suggestion would be much appreciated.

Many thanks

Upvotes: 0

Views: 153

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389045

Don't mix base R with tidyverse, {{}} is from tidyverse. You can use reformulate to create formula object and use it.

explore = function(var, title) {
  formula1 <- reformulate(var, 'y')
  formula2 <- reformulate('y', var)
  par(mfrow=c(1,2))
  tr = rpart(formula1, data = df)
  plot(tr, margin = .1, uniform = TRUE, main = title)
  text(tr, fancy = TRUE, use.n = TRUE)
  stripchart(formula2, main = title, data = df, method = "stack")
  boxplot(formula2, data = df)
}

Upvotes: 1

Related Questions