[R] Question about creating lists with functions as elements
Craig P. Pyrame
crappyr at gmail.com
Tue Jun 30 14:00:27 CEST 2009
Dear list,
I am trying to construct a list of functions using rep. I can't
understand the following:
> c(character, character) => list with two functions
> rep(character, 2) => error
The error says that "object of type 'special' is not subsettable", and I
have no idea what this means. Would you please help me.
The purpose of doing the above is that I need to use scan for reading
files that happen to be too large and a bit irregular for read.table.
To make scan work, I need to specify the types of values in each column
(record field). I can specify the 'what' argument as follows:
> records <- scan(..., what = list(character(0), character(0),
integer(0), numeric(0), character(0), ...), ...)
but this quickly becomes boring for large enough records. (Why does not
scan take a character string with class names, as read.table does,
instead of a list with dummy objects?) So I am trying to do tricks, and
one idea that seems pretty simple is to create a list of functions that
create vectors of a particular type, and apply them (using lapply) to
get a list of prototype objects:
> types = lapply(c(rep(character, 2), integer, numeric, ...),
function(type) type(0)) => error
But this fails, as above. Why? Why can c(character, character) create
a list of two functions, but rep(character, 2) can't?
Another solution to my problem I could find (and you'll hopefully
suggest an even better one) is to use class names instead, like so:
> types = lapply(c(rep('character', 2), 'integer', 'numeric', ...),
function(type) vector(type, 0))
but I am still curious why the above doesn't work as I would expect it to.
Best regards,
Craig
More information about the R-help
mailing list