別再 paste,開始用 glue
paste() 函式會用空白把字串串接在一起,所以 paste("Hi", "there") 的輸出是 "Hi there"。另外還有 paste0() 函式不會加空白,結果會是 "Hithere"。但當你要把多個字串與變數串起來時,就會寫出一堆雙引號 " 和逗號 ,,讓程式碼很難讀。而且你只能使用已存在的變數。
這正是 glue() 大顯身手的兩種情境。你可以直接使用全域範圍裡的變數,或是立即動態建立變數。在本練習中,你會實際看到 paste() 和 glue() 的差別。
本練習屬於課程
R 中級 Regular Expressions
練習說明
- 使用
glue()重新建立用paste0()產生的那個句子。 - 建立一個暫時變數
n,用來儲存firstname的字元長度,並將它傳入正在建立的句子中。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
firstname <- "John"
lastname <- "Doe"
paste0(firstname, "'s last name is ", lastname, ".")
# Create the same result as the paste above with glue
glue("___'s last name is ___.")
# Create a temporary varible "n" and use it inside glue
glue(
"The name {firstname} consists of ___ characters.",
___ = nchar(firstname)
)