[Rcpp-devel] List of Lists to List of Vectors

William Dunlap wdunlap at tibco.com
Sat May 2 19:49:24 CEST 2015


Here is one way to do it in R.  Much of the code is checking that the
format of 'x'
is what you describe and you may omit it if you know that does not need
checking.
The call to 'unlist' in the call to lapply is responsible for setting the
classes of the outputs.

Since translation from R to Rcpp is "seamless" I will leave that to you.

First an example:
  > X <- list(list(factor("a",levels=letters[1:5]), 1+1i, FALSE),
                list(factor("b",levels=letters[1:5]), 2+2i, TRUE))
  > f(X, check=TRUE)
  [[1]]
  [1] a b
  Levels: a b c d e

  [[2]]
  [1] 1+1i 2+2i

  [[3]]
  [1] FALSE  TRUE

Then the function:

f <- function(x, check = FALSE) {
   if (check) {
      stopifnot(
         is.list(x),
         all(vapply(x, is.list, FUN.VALUE=FALSE)),
         length(unique(vapply(x, length, FUN.VALUE=0)))==1)
   }
   listLength <- length(x)
   if (listLength == 0) {
      return(list())
   }
   elementLength <- length(x[[1]])
   xMatrix <- array(unlist(x, recursive=FALSE), dim=c(elementLength,
listLength))
   if (check) {
      # TODO: this rejects mixtures of numerics and integers,
      # but accepts mixtures of factors with different levels.
      elementSignature <- function(e) paste(collapse=",", unlist(lapply(e,
class)))
      stopifnot(length(unique(vapply(x, elementSignature,
FUN.VALUE="")))==1)
   }
   lapply(seq_len(nrow(xMatrix)), function(i)unlist(xMatrix[i,]))
}


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, May 1, 2015 at 7:28 PM, Tim Keitt <tkeitt at utexas.edu> wrote:

> If I have data like
>
> list(list('a', 1, T), list('b', 2, F), ...)
>
> (list of lists with same types)
>
> and I want to convert to
>
> list(c('a', 'b'), c(1, 2), c(T, F))
>
> (list of vectors)
>
> where the types are not known in advance (its trivial if you know the
> sequence of types in advance).
>
> Anyone know how to do that in Rcpp?
>
> THK
>
> --
> http://www.keittlab.org/
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150502/ba24d088/attachment.html>


More information about the Rcpp-devel mailing list