[R] mapping between list and vector

Adams, Jean jvadams at usgs.gov
Thu Oct 29 21:42:29 CET 2015


Maxim,

I'm not sure how much faster this would be ... but you could test it out
and see.  I defined lngL and result as vectors instead of lists.  And I
calculated j outside of the "loop".

myList <- list(a="key1", b=c("key2","key3"), c="key4")
myVec <- c("val1","val2","val3","val4")

lngL <- sapply(myList, length)
L <- length(lngL)
j <- cumsum(c(1, lngL))[1:L]
result <- sapply(1:L, function(i) paste(myVec[j[i]:(j[i] - 1 + lngL[i])],
collapse="//"))

Jean

On Thu, Oct 29, 2015 at 2:34 PM, Maxim via R-help <r-help at r-project.org>
wrote:

> Hi,
>
> for some reason I have to map elements of a list "myList" (of vectors of
> different length) to a vector "myVec" as such:
>
> myList <- list(a="key1", b=c("key2","key3"), c="key4")
> myVec <- c("val1","val2","val3","val4")
>
>
> result <- list()
> lapply(myList,length) -> lngL
>
> j <- 1
> for (i in 1:(length(lngL))) {
> result[[i]] <- paste(myVec[j:(j-1+lngL[[i]])],collapse="//")
> j <- j+lngL[[i]]
> }
>
> that the result looks like this:
>
> > result
>
> [[1]]
> [1] "val1"
>
> [[2]]
> [1] "val2//val3"
>
> [[3]]
> [1] "val3"
>
> Above code is the fastest version I was able to come up with (the list
> contains about 1 million elements). I guess the for loop can be substituted
> by a lapply command making it less complicated and probably faster, but I
> can't figure out how to do this in a more elegant and especially faster
> fashion.
>
> Best
> Maxim
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list