Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate vector elements in groups

What is the most elegant way of converting list1 to list2, and also list2 to list1?

list1<- c('a','b','c','d','e','f','g','h','i')
list2<- c('abc','def','ghi')

i.e: contactenate elements in groups of three.

thanks :D

like image 250
eye_mew Avatar asked Sep 12 '26 02:09

eye_mew


1 Answers

Let list1 <- letters[1:10] (to show how it works when the length of the vector is not a multiple of 3). Then, try this:

list1 to list2

# method 1 (seems to be the fastest so far, 
# my suspicions about loop being slower were wrong)
list2 <- sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = "")
# alternatively as @flodel mentions
list2 <- tapply(list1, (seq_along(list1)-1) %/% 3, paste, collapse = "")

The tapply version runs at a similar time as sapply+split (benchmarking not shown).

Going one step further, using @JoshOBrien's idea in this post

# method 2
pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc" "def" "ghi" "j"  

And if you want to get the last part concatenated to the last-but-one (here the j to ghi) then, do:

pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]]{3})"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc"  "def"  "ghij"

list2 to list1

unlist(strsplit(list2, ""), use.names=FALSE)
#  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

Here's a benchmarking of method1, method2 and eddi's:

data:

list1 <- sample(letters, 1e5, replace=TRUE)

functions:

arun <- function() {
    pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
    strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
}

arun2 <- function() {
    unname(sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""))
}

eddi <- function() {
    substring(paste(list1, collapse = ""),
          seq(1, length(list1), 3),
          pmin(seq(3, length(list1)+2, 3), length(list1)))    
}

benchmarking:

require(microbenchmark)
microbenchmark(t1 <- arun(), t2 <- eddi(), t3 <- arun2(), times=10)
identical(t1, t2) # TRUE
identical(t1, t3) # TRUE

# Unit: milliseconds
#           expr       min        lq    median        uq       max neval
#   t1 <- arun() 3352.9867 3400.8627 3512.7037 3585.6499 3635.2182    10
#   t2 <- eddi() 3302.0925 3318.4184 3356.2109 3409.9728 3487.7220    10
#  t3 <- arun2()  474.9235  494.7407  539.4406  641.2605  907.9072    10
like image 183
Arun Avatar answered Sep 13 '26 17:09

Arun