Skip to content

Pb with lapply()

4 messages · Hervé Pagès, Gabor Grothendieck

#
Hi,

If needed, lapply() tries to convert its first argument into a list
before it starts doing something with it:

  > lapply
  function (X, FUN, ...) 
  {
    FUN <- match.fun(FUN)
    if (!is.vector(X) || is.object(X)) 
        X <- as.list(X)
    .Internal(lapply(X, FUN))
  }

But in practice, things don't always seem to "work" as suggested by
this code (at least to the eyes of a naive user).

I have defined an "as.list" method for my S4 class "A":

  > setClass("A", representation(data="list"))
  [1] "A"
  > setMethod("as.list", "A", function(x, ...) x at data)
  Creating a new generic function for "as.list" in ".GlobalEnv"
  [1] "as.list"

Testing it:

  > a <- new("A", data=list(8, 2:0))
  > as.list(a)
  [[1]]
  [1] 8

  [[2]]
  [1] 2 1 0

OK.

But lapply() doesn't work on 'a':

  > lapply(a, typeof)
  Error in as.vector(x, "list") : cannot type 'S4' coerce to vector

I still have to do the 'as.list(a)' part myself for things to work:

  > lapply(as.list(a), typeof)
  [[1]]
  [1] "double"

  [[2]]
  [1] "integer"

Seems like using force() inside lapply() would solve the problem:

  lapply2 <- function(X, FUN, ...)
  {
    FUN <- match.fun(FUN)
    if (!is.vector(X) || is.object(X))
        X <- force(as.list(X))
    .Internal(lapply(X, FUN))
  }

It works now:

  > lapply2(a, typeof)
  [[1]]
  [1] "double"

  [[2]]
  [1] "integer"

Cheers,
H.
#
The problem of promises not being evaluated in
lists has been discussed before.

I think its fixed in the development version of R. See
r44139 on Jan 24, 2008 in http://developer.r-project.org/R.svnlog.2007
On Jan 31, 2008 1:26 PM, <hpages at fhcrc.org> wrote:
#
Hi Gabor,

Quoting Gabor Grothendieck <ggrothendieck at gmail.com>:
I'm using R-devel r44238 and the problem is still here.

Cheers,
H.
R version 2.7.0 Under development (unstable) (2008-01-29 r44238) 
x86_64-unknown-linux-gnu 

locale:
LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
#
I just checked and the
code that previously triggered the promises in lists
bug seems to work now so I guess it is a different
problem.

# code below previously triggered errors but now works
# R 2.6.2 (2008-01-26 r44181) on Vista
f <- function(x) environment()
z <- as.list(f(7))
dput(z)
structure(list(x = 7), .Names = "x")
z[[1]] == 7
force(z[[1]]) == 7
On Jan 31, 2008 2:33 PM, <hpages at fhcrc.org> wrote: