Home > Blockchain >  How to interleave vector of strings with a string
How to interleave vector of strings with a string

Time:02-03

I have the following vectors example:

v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")

Note that the length of each vector can be varied.

What I want to do is to interleave each vector with a string:

linker <- "xxx"

Resulting in this:

c("AA", "xxx", "BB")
c("AA","xxx",  "BB", "xxx", "CCC")

How can I achieve that?

CodePudding user response:

You could use an rbind trick here:

v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")
linker <- "xxx"

head(c(rbind(v2, linker)), -1)

[1] "AA"  "xxx" "BB"  "xxx" "CCC"

CodePudding user response:

Here you have a possible answer:

v1 <- c("AA", "BB")

v2 <- c("AA", "BB", "CCC")

linker <- "xxx"

interleave <- function(v,l){

  result <- c()
  
  for(i in 1:length(v)){
    
    if(i!=1){
      
      result <- c(result,l,v[i])
      
    }else{
      
      result <- c(result,v[i])
      
    }
    
  }
  
  return(result)
  
}

interleave(v1,linker)

interleave(v2,linker)

Results:

> interleave(v1,linker)
[1] "AA"  "xxx" "BB" 
> 
> interleave(v2,linker)
[1] "AA"  "xxx" "BB"  "xxx" "CCC"

CodePudding user response:

We can use append, and then head to remove the trailing linker:

append_linker <- function(vector, linker){
lapply(vector, \(x) append(x, linker)) |>
        unlist() |>
        head(-1)
}

append_linker(v1, linker)

[1] "AA"  "xxx" "BB" 

append_linker(v2, linker)

[1] "AA"  "xxx" "BB"  "xxx" "CCC"

CodePudding user response:

A creative application of mapply and c:

v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")
linker <- 'xxx'

c(mapply(c, linker, v1))[-1]

[1] "AA"  "xxx" "BB"

c(mapply(c, linker, v2))[-1]

[1] "AA"  "xxx" "BB"  "xxx" "CCC"
  •  Tags:  
  • Related