繁体   English   中英

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

[英]Removing characters from string in R

我的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或者组合来尝试它,但从来没有完全奏效。

我的错误在哪里?

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

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

尝试

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"

另一种选择是使用stripqdap

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM