一个单词字符串在R中向量

时间:2015-10-08 18:29:35

标签: r string vector

有一个像

这样的字符串
"xzyyzyzyxyyyxxxyzzyzzzxzyxxzzzyzyxyxxxxyxxyxxyxyyzxyzzyzzxyxyyzxzzxyxxyxxzyxyzyxzzyzxxyzyzyyyzxxxzxx"

如何将其转换为以下矢量:

"x","z","y","y","z","y","z","y","x","y","y","y","x","x","x","y","z","z","y","z","z","z","x","z","y","x","x","z","z","z","y","z","y","x",","y",","x","x","x","x",","y",","x","x",","y",","x","x",","y",","x","y","y","z","x","y","z","z","y","z","z","x",","y",","x","y","y","z","x","z","z","x",","y",","x","x",","y",","x","x","z","y","x","y","z","y","x","z","z","y","z","x","x","y","z","y","z","y","y","y","z","x","x","x","z","x","x"

我无法做到

unlist(strsplit("thestring", split=""))

1 个答案:

答案 0 :(得分:4)

你可以尝试:

strsplit("xzyyzyzyxyyyxxxyzzyzzzxzyxxzzzyzyxyxxxxyxxyxxyxyyzxyzzyzzxyxyyzxzzxyxxyxxzyxyzyxzzyzxxyzyzyyyzxxxzxx", "")
[[1]]
[1] "x" "z" "y" "y" "z" "y" "z" "y" "x" "y" "y" "y" "x" "x" "x" "y" "z" "z" "y" "z" "z" "z" "x" "z" "y" "x" "x" "z" "z" "z" "y" "z" "y" "x" "y" "x" "x" "x" "x"
[40] "y" "x" "x" "y" "x" "x" "y" "x" "y" "y" "z" "x" "y" "z" "z" "y" "z" "z" "x" "y" "x" "y" "y" "z" "x" "z" "z" "x" "y" "x" "x" "y" "x" "x" "z" "y" "x" "y" "z"
[79] "y" "x" "z" "z" "y" "z" "x" "x" "y" "z" "y" "z" "y" "y" "y" "z" "x" "x" "x" "z" "x" "x"

分配给新的载体:

x <- strsplit("xzyyzyzyxyyyxxxyzzyzzzxzyxxzzzyzyxyxxxxyxxyxxyxyyzxyzzyzzxyxyyzxzzxyxxyxxzyxyzyxzzyzxxyzyzyyyzxxxzxx", "")
str(x)
#List of 1
# $ : chr [1:100] "x" "z" "y" "y" ...
is.vector(x)
#[1] TRUE

如果您想使用thestring作为对象的名称,则必须以类似的方式完成:

thestring <- "xzyyzyzyxyyyxxxyzzyzzzxzyxxzzzyzyxyxxxxyxxyxxyxyyzxyzzyzzxyxyyzxzzxyxxyxxzyxyzyxzzyzxxyzyzyyyzxxxzxx"
strsplit(thestring, "")

请注意,您也可以将此输出另存为另一个对象:

thestring2 <- strsplit(thestring, "")
#You can 'rename' the same object too, bear in mind you would have to assign the actual "xzyy..." to `thestring` first:
thestring <- strsplit(thestring, "")