Hans
Hans

Reputation: 5505

In R, how can a string be split without using a seperator

i am try split method and i want to have the second element of a string containing only 2 elemnts. The size of the string is 2.

examples :

string= "AC"

result shouldbe a split after the first letter ("A"), that I get :

res=    [,1] [,2]
     [1,] "A" "C"

I tryed it with split, but I have no idea how to split after the first element??

Upvotes: 2

Views: 488

Answers (3)

Marek
Marek

Reputation: 50704

If you sure that it's always two char string (check it by all(nchar(x)==2)) and you want only second then you could use sub or substr:

x <- c("ab", "12")
sub(".", "", x)
# [1] "b" "2"
substr(x, 2, 2)
# [1] "b" "2"

Upvotes: 0

Gavin Simpson
Gavin Simpson

Reputation: 174798

strsplit() will do what you want (if I understand your Question). You need to split on "" to split the string on it's elements. Here is an example showing how to do what you want on a vector of strings:

strs <- rep("AC", 3) ## your string repeated 3 times

next, split each of the three strings

sstrs <- strsplit(strs, "")

which produces

> sstrs
[[1]]
[1] "A" "C"

[[2]]
[1] "A" "C"

[[3]]
[1] "A" "C"

This is a list so we can process it with lapply() or sapply(). We need to subset each element of sstrs to select out the second element. Fo this we apply the [ function:

sapply(sstrs, `[`, 2)

which produces:

> sapply(sstrs, `[`, 2)
[1] "C" "C" "C"

If all you have is one string, then

strsplit("AC", "")[[1]][2]

which gives:

> strsplit("AC", "")[[1]][2]
[1] "C"

Upvotes: 5

joran
joran

Reputation: 173537

split isn't used for this kind of string manipulation. What you're looking for is strsplit, which in your case would be used something like this:

strsplit(string,"",fixed = TRUE)

You may not need fixed = TRUE, but it's a habit of mine as I tend to avoid regular expressions. You seem to indicate that you want the result to be something like a matrix. strsplit will return a list, so you'll want something like this:

strsplit(string,"",fixed = TRUE)[[1]]

and then pass the result to matrix.

Upvotes: 2

Related Questions