Search code examples
rstringstrsplit

Why does paste() concatenate list elements in the wrong order?


Given the following string:

my.str <- "I welcome you my precious dude"

One splits it:

my.splt.str <- strsplit(my.str, " ")

And then concatenates:

paste(my.splt.str[[1]][1:2], my.splt.str[[1]][3:4], my.splt.str[[1]][5:6], sep = " ")

The result is:

[1] "I you precious"  "welcome my dude"

When not using the colon operator it returns the correct order:

paste(my.splt.str[[1]][1], my.splt.str[[1]][2], my.splt.str[[1]][3], my.splt.str[[1]][4], my.splt.str[[1]][5], my.splt.str[[1]][6], sep = " ")

[1] "I welcome you my precious dude"

Why is this happening?


Solution

  • paste is designed to work with vectors element-by-element. Say you did this:

    names <- c('Alice', 'Bob', 'Charlie')
    paste('Hello', names)
    

    You'd want to result to be [1] "Hello Alice" "Hello Bob" "Hello Charlie", rather than "Hello Hello Hello Alice Bob Charlie".

    To make it work like you want it to, rather than giving the different sections to paste as separate arguments, you could first combine them into a single vector with c:

    paste(c(my.splt.str[[1]][1:2], my.splt.str[[1]][3:4], my.splt.str[[1]][5:6]), collapse = " ")
    ## [1] "I welcome you my precious dude"