从R中的字符串中删除字符

时间:2014-11-20 16:32:38

标签: r string

我的R输出中有一些标签或空格(我怀疑输出来自的任务中的问题),使它看起来像这样:

[1841] "\t\t\tGreen\n\t\t"         
[1842] "Blue"                       
[1843] "\t\t\tRed\n\t\t" 

对于同事,我必须将其读入SPSS,并且在将其作为txt数据读取时会出现问题,因此我想删除字符串中的\ t和\ n部分:

str_replace(mydata, "([\n])", "")

用\ n和\ t或\ t组合来尝试它,但从未完全奏效。

我的错误在哪里?

2 个答案:

答案 0 :(得分:10)

您需要使用str_replace_all删除空白字符的多个帐户。为什么不使用基数R来删除这些字符而不是加载stringr包?

gsub('[\t\n]', '', mydata)

答案 1 :(得分:7)

尝试

library(stringr)
str1 <- c("\t\t\tGreen\n\t\t", "Blue",  "\t\t\tRed\n\t\t" )
str_replace_all(str1, "([\n\t])", "")

#[1] "Green" "Blue"  "Red"  

或使用stringi

library(stringi)
stri_replace_all_regex(str1, "[\n\t]", "")
#[1] "Green" "Blue"  "Red"  

更新

假设,如果字符串中有多个单词,gsubstr_replace_all将提供相同的输出。

x <- c("\t\t\tGreen\n\t\t", "Blue", "\t\t\tRed\n\t\t yellow")
str_replace_all(x, '[\n\t]', '')
#[1] "Green"      "Blue"       "Red yellow"

另一种选择是使用strip

中的qdap
library(qdap)
strip(x, lower.case=FALSE)
#[1] "Green"      "Blue"       "Red yellow"
## Or...
Trim(clean(x))
#[1] "Green"      "Blue"       "Red yellow"