开发者

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

开发者 https://www.devze.com 2023-04-01 15:13 出处:网络
i am try split method and i want to have the secon开发者_运维技巧d element of a string containing only 2 elemnts. The size of the string is 2.

i am try split method and i want to have the secon开发者_运维技巧d 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??


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"


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.


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消