How make a new vector grouping the elementes of a known vector 2 by 2)

Hi, I am trying to make a new vector joing its values 2 by 2 (os n by n) using a loop, but I cant
An example:

c <- (a,b,f,g,t,h), then the new vector is (ab, fg, th). I am using a loop becouse I dont know any tool to do it

This is my atempt:

n <- 100
m <- n-2
s <- seq(from = 1, to = m, by = 2 )
flips = sample(c(1,0), replace=TRUE, size=n)
a <- as.character(seq(from = 1, to = m, by =2))

for (i in s) {
x=flips[i]
y=flips[(i+1)]
for (j in 1:length(s)){
a[j] <- paste(x, y, sep = "-" )
}
}
Can someone help me?

thanks in advance. Javi

Hi @pavili,
Try this approach using a matrix as an intermediate object:

AA <- c("a","b","f","g","t","h")
mat <- matrix(data=AA, ncol=2, byrow=TRUE)
mat
#>      [,1] [,2]
#> [1,] "a"  "b" 
#> [2,] "f"  "g" 
#> [3,] "t"  "h"
new <- paste0(mat[,1], mat[,2])
new
#> [1] "ab" "fg" "th"

# Put this approach into a function and generalise for n
paste_by_n <- function(x, n=2) {
  if((length(x) %% n) != 0) stop("Length of input string must be multiple of join size")
  mat <- matrix(data=AA, ncol=n, byrow=TRUE)
  apply(mat[,1:n] , 1, paste , collapse = "")
}

paste_by_n(AA)   # n=2 is the default argument
#> [1] "ab" "fg" "th"
paste_by_n(AA, n=3)
#> [1] "abf" "gth"
paste_by_n(AA, n=4)
#> Error in paste_by_n(AA, n = 4): Length of input string must be multiple of join size

Created on 2021-09-16 by the reprex package (v2.0.1)

Hi @DavoWW , thanks for your helping. Your helping was decisive to make the exercise I needed to build.

I is about flip dices and the probability for a combination.

I share it with you.

Thanks again!


#load library
library(stringr)

#define number of flips
h <- 100000

#define number of repetitions and the combination to choose
n=4

a='1-5-6-2' 

#flip the coin many times

m <- round(h/n,0)*n

flips = sample(c(1,2,3,4,5,6), replace=TRUE, size=m, prob = c(0.1666666666667, 0.16666666666667, 0.1666666666667, 0.166666666667, 0.16666666667, 0.16666666667))

# Put this approach into a function and generalise for n

mat <- matrix(data=flips, ncol=n, byrow=TRUE)

paste_by_n <- function(x, n) {
  if((length(x) %% n) != 0) stop("Length of input string must be multiple of join size")
  mat <- matrix(data=flips, ncol=n, byrow=TRUE)
  apply(mat[,1:n] , 1, paste  , collapse = "-")
}

combinations <- paste_by_n(flips, n)

#count the percent of times HEAD-HEAD-HEAD-HEAD appears
b=str_count(paste(combinations, collapse="*"), a) / (m/n)

paste("La probabilidad de sacar", a, "es del:", round(b*100,2), "%")