[英]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"
假設,如果字符串中有多個單詞,則gsub
和str_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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.