[R] mapping between list and vector

Maxim deeepersound at googlemail.com
Thu Oct 29 20:34:56 CET 2015


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]]



More information about the R-help mailing list