[R] dput( list(<S4>,..) ) could be improved

Martin Maechler maechler at stat.math.ethz.ch
Tue Jan 5 10:14:49 CET 2016


> > On Jan 4, 2016, at 11:17 PM, Lietz, Haiko <Haiko.Lietz at gesis.org> wrote:
> > 
> > hi all,
> > 
> > when dputting a list of sparse matrices (Matrix package), the output does not contain the data but the information that the list contains sparse matrices.
> > 
> > M <- sparseMatrix(i = c(2, 1), j = c(1, 2), x = c(1, 1))
> > 
> > dput(M) ... works.
> > 
> > dput(list(M, M)) ... does not work.
> > 
> > how can I dput a list of sparse matrices?

> > MM <- list(M,M)
> > dput(MM)
> list(<S4 object of class structure("dgCMatrix", package = "Matrix")>, 
>     <S4 object of class structure("dgCMatrix", package = "Matrix")>)

> No problem.

> I do get an error (clarifying the "did not work" statement), as (perhaps) did you?

> > dput(M,M)
> Error in cat("new(\"", clx, "\"\n", file = file, sep = "") : 
>   invalid connection

> Perhaps the `dput` function was not configured to handle two S4 objects in  a list?

Indeed.  As a matter of fact,  a long time I ago I had added a 'FIXME'
comment to the R source code of dput:

see  https://svn.r-project.org/R/trunk/src/library/base/R/dput.R

which contains

    ## FIXME: this should happen in C {deparse2() in ../../../main/deparse.c}
    ##        but we are missing a C-level slotNames()
    ## Fails e.g. if an S3 list-like object has S4 components
    if(isS4(x)) {
	clx <- class(x)
	cat('new("', clx,'"\n', file = file, sep = "")
	for(n in methods::.slotNames(clx)) {
	    cat("    ,", n, "= ", file = file)
	    dput(methods::slot(x, n), file = file, control = control)
	}
	cat(")\n", file = file)
	invisible()
    }
    else .Internal(dput(x, file, opts))

Ideally the above code would be replaced by simply

    .Internal(dput(x, file, opts))

and the C code called in do_dput()  in
  https://svn.r-project.org/R/trunk/src/main/deparse.c
would be improved to do the above in C and be properly
recursive.

(Tested) patches are very welcome!

Martin Maechler,
ETH Zurich and R Core Team



More information about the R-help mailing list