Eduardo
Eduardo

Reputation: 2514

Create a list where each element is a pair of contiguous members from given vector

Or how to split a vector into pairs of contiguous members and combine them in a list?

Supose you are given the vector

map <-seq(from = 1, to = 20, by = 4)

which is

1  5  9  13  17

My goal is to create the following list

path <- list(c(1,5), c(5,9), c(9,13), c(13,17))

This is supposed to represent the several path segments that the map is sugesting us to follow. In order to go from 1 to 17, we must first take the first path (path[1]), then the second path (path[2]), and all the way to the end.

My first attempt lead me to:

path <- split(aux <- data.frame(S = map[-length(map)], E = map[-1]), row(aux))

But I think it would be possible without creating this auxiliar data frame and avoiding the performance decrease when the initial vector (the map) is to big. Also, it returns a warning message which is quite alright, but I like to avoid them.

Then I found this here on stackoverflow (not exactly like this, this is the adapted version for my problem):

mod_map <- c(map, map[c(-1,-length(map))])
mod_map <- sort(mod_map)
split(mod_map, ceiling(seq_along(mod_map)/2))

which is a simpler solution, but I have to use this modified version of my map.

Pherhaps I'm asking too much as I already got two solutions. But, could it be possible to have a third one, so that I don't have so use data frames as in my first solution and can use the original map, unlike my second solution?

Upvotes: 3

Views: 73

Answers (1)

akrun
akrun

Reputation: 886948

We can use Map on the vector ('map' - better not to use function names - it is a function from purrr) with 1st and last element removed and concatenate elementwise

Map(c, map[-length(map)], map[-1])

Or as @Sotos mentioned, split can be used which would be faster

split(cbind(map[-length(map)], map[-1]), seq(length(map)-1)) 

Upvotes: 2

Related Questions