strsplit 不能一直工作,字母之间的字符不是 space?
strsplit not consistently working, character between letters isn't a space?
问题很简单,但我没有运气解决它。 strsplit() 是一个相当简单的函数,我很惊讶我和我一样挣扎:
# temp is the problem string. temp is copy / pasted from my R code.
# i am hoping the third character, the space, which i think is the error, remains the error
temp = "GS PG"
# temp2 is created in Whosebug, using an actual space
temp2 = "GS PG"
unlist(strsplit(temp, split = " "))
[1] "GS PG"
unlist(strsplit(temp2, split = " "))
[1] "GS" "PG"
.
即使它在这里对我尝试重现示例不起作用,这也是我 运行 遇到的问题。对于 temp,由于某些奇怪的原因,代码没有在 space 上拆分变量。如有任何想法,我们将不胜感激!
最佳,
编辑 - 我的示例未能重现问题。作为参考,temp 是通过使用 rvest 从网上抓取代码在我的代码中创建的,出于某种原因,我认为它必须抓取不同于正常 space 的其他字符?不过,我需要将这些字符串拆分为 space。
尝试以下操作:
unlist(strsplit(temp, "\s+"))
"\s+"
是一个正则表达式搜索任何类型的白色 space 而不仅仅是标准的 space.
如评论中所述,
很可能 "space" 实际上不是 space 而是其他一些白色 space 字符。
尝试以下任一方法来缩小范围:
whitespace <- c(" ", "\t" , "\n", "\r", "\v", "\f")
grep(paste(whitespace,collapse="|"), temp)
相关问题在这里:
How to remove all whitespace from a string?
问题很简单,但我没有运气解决它。 strsplit() 是一个相当简单的函数,我很惊讶我和我一样挣扎:
# temp is the problem string. temp is copy / pasted from my R code.
# i am hoping the third character, the space, which i think is the error, remains the error
temp = "GS PG"
# temp2 is created in Whosebug, using an actual space
temp2 = "GS PG"
unlist(strsplit(temp, split = " "))
[1] "GS PG"
unlist(strsplit(temp2, split = " "))
[1] "GS" "PG"
.
即使它在这里对我尝试重现示例不起作用,这也是我 运行 遇到的问题。对于 temp,由于某些奇怪的原因,代码没有在 space 上拆分变量。如有任何想法,我们将不胜感激!
最佳,
编辑 - 我的示例未能重现问题。作为参考,temp 是通过使用 rvest 从网上抓取代码在我的代码中创建的,出于某种原因,我认为它必须抓取不同于正常 space 的其他字符?不过,我需要将这些字符串拆分为 space。
尝试以下操作:
unlist(strsplit(temp, "\s+"))
"\s+"
是一个正则表达式搜索任何类型的白色 space 而不仅仅是标准的 space.
如评论中所述,
很可能 "space" 实际上不是 space 而是其他一些白色 space 字符。 尝试以下任一方法来缩小范围:
whitespace <- c(" ", "\t" , "\n", "\r", "\v", "\f")
grep(paste(whitespace,collapse="|"), temp)
相关问题在这里: How to remove all whitespace from a string?