strsplit()在字符串的开头和结尾处的行为与空格不同

时间:2015-11-11 12:01:56

标签: r strsplit

根据拆分条件(' ')是否位于字符串的开头或结尾,它将显示为输出列表中的项目。

#strsplit("This is a string ")

strsplit("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string"

#strsplit(" And this is a string", ' ')
strsplit(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"      "string"

有没有办法更改此代码,以便空间显示为两个列表的项目?

预期输出:

#strsplit("This is a string ")

strsplit("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string" "" 

#strsplit(" And this is a string", ' ')
strsplit(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"      "string"

1 个答案:

答案 0 :(得分:4)

使用stringi::stri_split

require(stringi)
stri_split_fixed("This is a string ", ' ')
#[[1]]
#[1] "This"   "is"     "a"      "string" ""      

stri_split_fixed(" And this is a string", ' ')
#[[1]]
#[1] ""       "And"    "this"   "is"     "a"     
#[6] "string"