Error when installing: cannot coerce type 'closure' to vector of type 'character'

user7789 picture user7789 · May 24, 2014 · Viewed 58.1k times · Source

Tried to install all rattle related packages by typing:

install.packages(rattle, dependencies = c("Depends","Suggests"))

and got this

Installing package into ‘C:/Users/Hooman/Documents/R/win-library/3.1’
(as ‘lib’ is unspecified)
Error in as.character(x) : 
  cannot coerce type 'closure' to vector of type 'character'

I already installed two individual packages in that folder and had no issue.

Answer

IRTFM picture IRTFM · May 24, 2014

@BenBolker posted an answer as a comment, perhaps because he is hoping that you will stare at the difference between your code and his and get a Zen-moment. He also thinks, being the modest gentleman that he is, that it's too simple to warrant any upvotes. So I am feeling guilty that any upvotes are his rather than mine. I will now try to legitimately earn any upvotes.

The reason you got the error was the the install.packages function expects a character object, while you gave it the unquoted expression rattle. Ben uses a single element character vector "rattle", thus conforming to the requirement of the function. Unlike some functions install.packages is not equipped to provide "non-standard evaluation" of its first argument.

R is a funny language at times with some inconsistent evaluation conventions. There are several functions where you can provide an unquoted expression and have it automatically converted to character. The list includes library, and its cousin, require, as well as help, subset, and $. These are considered "non-standard" evaluation by knowledgeable users, and they can have their pitfalls in programming. The error message tells you that R tried to convert what it "thought" would be a language object, a closure (which loosely is an R and LiSP term for function), to a character and did not succeed. You can see the same error with this console interaction:

> as.character(mean)
Error in as.character(mean) : 
  cannot coerce type 'closure' to vector of type 'character'

If you look at the library function mentioned by Ben and scroll down past the internal function definitions you eventually get to the mechanism whereby library avoids that error:

if (!character.only) 
            package <- as.character(substitute(package))

This would also avoid the error, which I intentionally used as an example:

> as.character(substitute(mean))
[1] "mean"

The substitute function is doing processing on a language element taken to be a closure and the resulting object an R "name" has an as.character method.