Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split up a character in R?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading