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
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), "%")