1

If I have a datafram containing a column: "AA", "BB", "AB"....

combination.a <- apply(combn(LETTERS[1:8],2),2,paste0,collapse="")
combination.b <- apply(combn(LETTERS[8:1],2),2,paste0,collapse="")
combination <- c(combination.a,combination.b)

and want to get two new columns "A" "B" "A"... & "A" "B" "B"...

How should I execute it?

jpsmith
  • 11,023
  • 5
  • 15
  • 36

1 Answers1

1

You can use tidyr::separate and separate after the first position, though your data need to be in a data frame (combination2):

library(tidyr)
combination2 <- data.frame(combination)
combination2 %>% separate(combination, into = c("sep.1", "sep.2"), sep = 1)

output:

#    sep.1 sep.2
# 1      A     B
# 2      A     C
# 3      A     D
# 4      A     E
# 5      A     F
# 6      A     G
# 7      A     H
# 8      B     C
# 9      B     D
# 10     B     E

A base R approach would be to use strsplit and do.call with rbind on the original combination

do.call(rbind, strsplit(combination, split = ""))

Output

#     [,1] [,2]
# [1,] "A"  "B" 
# [2,] "A"  "C" 
# [3,] "A"  "D" 
# [4,] "A"  "E" 
# [5,] "A"  "F" 
# [6,] "A"  "G" 
# [7,] "A"  "H" 
# [8,] "B"  "C" 
# [9,] "B"  "D" 
# [10,] "B"  "E" 
jpsmith
  • 11,023
  • 5
  • 15
  • 36