《Learning R》筆記 Chapter 7 上 String

構(gòu)筑/連接

構(gòu)筑一個(gè)string類型的vector,最常用的是c()函數(shù)。同時(shí)paste()函數(shù)也很常用。

paste (..., sep = " ", collapse = NULL)
paste0(..., collapse = NULL) #默認(rèn)不間隔
# sep : a character string to separate the terms.
#collapse : an optional character string to separate the results
> paste(letters[2:6] , '1' , sep='$')
[1] "b$1" "c$1" "d$1" "e$1" "f$1"
> paste(letters[2:6] , '1' , sep='$' , collapse = '+')
[1] "b$1+c$1+d$1+e$1+f$1" #collapse使用的字符不會在最后出現(xiàn)
> paste(letters,sep = '',collapse = '')
[1] "abcdefghijklmnopqrstuvwxyz"
>paste(letters,letters,letters,sep = '+') #可以paste3個(gè)或3個(gè)以上的string
 [1] "a+a+a" "b+b+b" "c+c+c" "d+d+d" "e+e+e" "f+f+f" "g+g+g" "h+h+h" "i+i+i" "j+j+j" "k+k+k" "l+l+l"
[13] "m+m+m" "n+n+n" "o+o+o" "p+p+p" "q+q+q" "r+r+r" "s+s+s" "t+t+t" "u+u+u" "v+v+v" "w+w+w" "x+x+x"
[25] "y+y+y" "z+z+z"

toString()函數(shù)只接受一個(gè)string,輸出一個(gè)string。新的string格式更漂亮。

 > toString(letters) # 默認(rèn)使用逗號間隔
[1] "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"
> toString(letters , width = 20) #手動控制輸出長度
[1] "a, b, c, d, e, f...."

cat()是R的一個(gè)底層函數(shù)。print()等眾多函數(shù)都以其為基礎(chǔ)。
noquote()是print()的一個(gè)wrapper,能打印出無雙引號的字符串。

格式化/Formatting

R的底層是C,因此sprintf()函數(shù)能夠按照C風(fēng)格的通用格式來格式化字符串。formatC()函數(shù)也有類似功能。值得指出的是,這些R函數(shù)都是接受vector輸入的。

> sprintf('the value of num %s is %.2f.' , 1:3 , rnorm(3))
[1] "the value of num 1 is -0.03." "the value of num 2 is -0.23." "the value of num 3 is -0.20."

format()的語法類似于formatC() 。它和prettyNum()一樣能夠輸出格式更美觀的string。

特殊字符

\t是制表符,\n是換行,\才是普通的‘\’。這一點(diǎn)類似于其他語言。但這些特殊符號不能在print()下實(shí)現(xiàn)(會被轉(zhuǎn)換為普通字符),書里使用的是cat()函數(shù)。

大小寫

toupper() 和 tolower() 無需多言

提?。╡xtract)

提取單個(gè)字符串的一部分可以直接使用[],但要提取一個(gè)character vector時(shí),就要使用substr和substring兩個(gè)函數(shù)。二者在大部分時(shí)間是相似的,他們的細(xì)微差別在于:

For substr, a character vector of the same length and with the same attributes as x;
For substring, a character vector of length the longest of the arguments.

substr(x, start, stop)
substring(text, first, last = 1000000L) 
#換言之,如果first或last里輸入了比text還要長(length)的vector
#那么substring()的輸出會比text長。

切分/paste的反向操作

使用strsplit()可以進(jìn)行paste()的反向操作。需要注意的是,函數(shù)的輸出是一個(gè)list!,即使x的長度為1!

strsplit(x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)
#如果fixed=TRUE,則要求嚴(yán)格匹配split。否則split為正則表達(dá)式
> x='Thank you, voice of reason.'
> strsplit(x,',? ')
[[1]]
[1] "Thank"   "you"     "voice"   "of"      "reason."

文件路徑

在R中最好使用 / 來描述文件路徑。basename() 和 dirname()可以查看文件路徑的不同部分。

> x <- 'E:/Steam/steamapps/common/Fallout New Vegas/nvse_loader.exe'
> basename(x) ; dirname(x)
[1] "nvse_loader.exe"
[1] "E:/Steam/steamapps/common/Fallout New Vegas"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容