Adrian Smith
Adrian Smith

Reputation: 139

Split a single variable-multi character vector into chunks

Although simple, I couldn't find a robust solution.

I have a single variable-multi character vector (i.e. "ABCDEFGHI"), that I'm looking to split into a multi single-letter vector (i.e. c("A", "B", "C", "D", "E", "F", "G", "H", "I") ).

Is there a single function capable of that? or should I put my effort into writing a function for that?

Upvotes: 2

Views: 68

Answers (3)

MKR
MKR

Reputation: 20085

One can use regmatches and to match any word character using \w expression.

str <- "ABCDEFG"
regmatches(str, gregexpr("\\w",str))[[1]]
#[1] "A" "B" "C" "D" "E" "F" "G"

Upvotes: 1

Roman
Roman

Reputation: 17648

You can use the stringr function str_split as well

library(stringr)
str_split(str1, "", simplify = T)[1,]
[1,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"

Upvotes: 2

akrun
akrun

Reputation: 886968

We can use strsplit from R

strsplit(str1, "")[[1]]
#[1] "A" "B" "C" "D" "E" "F" "G" "H" "I"

In python, cast to list

list("ABCDEFGH")
#['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

data

str1 <- "ABCDEFGHI"

Upvotes: 3

Related Questions