kuki
kuki

Reputation: 313

invalid 'envir' argument of type 'character' -- in self-defined function with lattice histogram

I want a function with parameters such as data name (dat), factor(myfactor), variable names(myvar) to dynamically generate histograms (have to use lattice).

Using IRIS as a minimal example:

data(iris)



my_histogram <- function(myvar,myfactor,dat){
    listofparam <- c(myvar,myfactor)
    myf <- as.formula(paste("~",paste(listofparam,collapse="|")))
    histogram(myf,
              data=dat,
              main=bquote(paste(.(myvar),"distribution by",.(myfactor),seq=" ")))}



my_histogram("Sepal.Length","Species","iris") 

I also tried do.call as some posts indicated:

my_histogram <- function(myvar,myfactor,dat){
listofparam <- c(myvar,myfactor)
myf <- as.formula(paste("~",paste(listofparam,collapse="|")))
p <- do.call("histogram",
   args = list(myf,
   data=dat))
print(p)

}

my_histogram("Sepal.Length","Species","iris") 

But the error appears: invalid 'envir' argument of type 'character'. I think the program doesn't know where to look for thismyf` string. How can I fix this or there's a better way?

Upvotes: 1

Views: 23919

Answers (1)

IRTFM
IRTFM

Reputation: 263411

Readers of this should be aware that the question has completely mutated from an earlier version and doesn't really match up with this answer anymore. The answer to the new question appears in the comments.

There is no object named Sepal.Length. (So R is creating an error even before that my_function gets called.) There is only a column name and it would need to be quoted to pass it to a function. (The data object could not be created because that URL fails to deliver the data. Why aren't you using the built-in copy of the iris data object?

You will also need to build a formula from myvar and fac. Formulas are expressions and get parsed without evaluation of their tokens. You need to build a formula inside your function that looks like: ~Sepal.Length|Species and then pass it to the histogram call. Consult ?as.formula

Upvotes: 2

Related Questions