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

ben*_*ron 6 string r

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

[1841] "\t\t\tGreen\n\t\t"         
[1842] "Blue"                       
[1843] "\t\t\tRed\n\t\t" 
Run Code Online (Sandbox Code Playgroud)

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

str_replace(mydata, "([\n])", "")
Run Code Online (Sandbox Code Playgroud)

用\n和\ t或者组合来尝试它,但从来没有完全奏效.

我的错误在哪里?

hwn*_*wnd 11

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

gsub('[\t\n]', '', mydata)
Run Code Online (Sandbox Code Playgroud)


akr*_*run 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"  
Run Code Online (Sandbox Code Playgroud)

或使用 stringi

library(stringi)
stri_replace_all_regex(str1, "[\n\t]", "")
#[1] "Green" "Blue"  "Red"  
Run Code Online (Sandbox Code Playgroud)

更新

假设,如果字符串中有多个单词,则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"
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用stripqdap

library(qdap)
strip(x, lower.case=FALSE)
#[1] "Green"      "Blue"       "Red yellow"
## Or...
Trim(clean(x))
#[1] "Green"      "Blue"       "Red yellow"
Run Code Online (Sandbox Code Playgroud)