Is the an R function to "multiply" individual characters in a string?

Viewed 37
string1 <- c("AB", "CD", "EF")
string2 <- c("E", "GH)

string1 string2 output

AB      E       AE, BE
CD      GH      CG, CH, DG, DH
EF              E, F

For row 1, it could be either A and B, but never A and B with E.

This is what I have so far:

unique(strsplit(x, ""))

[[1]]
[1] "A" "B"

[[2]]
[1] "E"

I also know I have to use the combn() function, but I'm not sure how.

1 Answers

After splitting the two strings with "", use Map to loop over the corersponding elements, create a matrix of combinations with outer, while specifying the FUN as paste to concat the individual elements, unlist the list output after pasteing the vector of strings to a single string (toString) and create a data.frame with the strings and the output as columns

output <- unlist(Map(function(x, y) toString(sort(c(outer(x, 
    if(length(y) == 0) "" else y, FUN = paste0)))), 
        strsplit(string1, ""), strsplit(string2, "")))

data.frame(string1, string2, output)
#  string1 string2         output
#1      AB       E         AE, BE
#2      CD      GH CG, CH, DG, DH
#3      EF                   E, F

NOTE: The if make sure that if there is string with only blank ("") element, it won't return character(0)


If there are more than 2 strings, use expand.grid

library(dplyr)
library(purrr)
output <-  mget(ls(pattern = "^string\\d+$")) %>% 
    transpose %>% 
    map_chr(~ {
       x1 <- strsplit(unlist(.), "")
       x1[lengths(x1) == 0] <- ''
       expand.grid(x1) %>% 
           invoke(paste0, .) %>%
           toString
     } ) 

mget(ls(pattern = "^string\\d+$")) %>%
    as_tibble %>%
    mutate(output = output)

-output

# A tibble: 3 x 4
#  string1 string2 string3 output                                
#  <chr>   <chr>   <chr>   <chr>                                 
#1 AB      "E"     FH      AEF, BEF, AEH, BEH                    
#2 CD      "GH"    NG      CGN, DGN, CHN, DHN, CGG, DGG, CHG, DHG
#3 EF      ""      C       EC, FC    

data

string1 <- c("AB", "CD", "EF")
string2 <- c("E", "GH", "")
string3 <- c("FH", "NG", "C")
Related