在R中,如何在不使用分隔符的情况下分割字符串
我正在尝试 split 方法,我想要一个仅包含 2 个元素的字符串的第二个元素。字符串的大小是 2。
示例:
string= "AC"
结果应该是第一个字母(“A”)之后的分割,我得到:
res= [,1] [,2]
[1,] "A" "C"
我尝试使用分割,但我不知道如何在第一个元素之后分割?
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strsplit()
会做你想做的事(如果我理解你的问题)。您需要拆分""
来拆分其元素上的字符串。下面是一个示例,展示了如何对字符串向量执行您想要的操作:三个字符串中的每一个
接下来,拆分生成的
这是一个列表,因此我们可以使用
lapply()
或处理它>sapply()
。我们需要对 sstrs 的每个元素进行子集化以选择第二个元素。为此,我们应用[
函数:它会产生:
如果您只有一个字符串,那么
它会给出:
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:next, split each of the three strings
which produces
This is a list so we can process it with
lapply()
orsapply()
. We need to subset each element ofsstrs
to select out the second element. Fo this we apply the[
function:which produces:
If all you have is one string, then
which gives:
split
不用于这种字符串操作。您正在寻找的是strsplit
,在您的情况下将使用如下内容:您可能不需要
fixed = TRUE
,但这是我的习惯,因为我倾向于避免正则表达式。您似乎表明您希望结果类似于矩阵。strsplit
将返回一个列表,因此您需要如下所示的内容:然后将结果传递给
matrix
。split
isn't used for this kind of string manipulation. What you're looking for isstrsplit
, which in your case would be used something like this: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:and then pass the result to
matrix
.如果您确定它始终是两个字符字符串(通过
all(nchar(x)==2)
检查)并且您只想要第二个,那么您可以使用sub
或 <代码>子字符串: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 usesub
orsubstr
: