問題
你想要通過變量創(chuàng)建一個(gè)字符串。
方案
兩種從變量創(chuàng)建字符串的通用方法是使用paste()和sprintf()函數(shù)。對向量來說,paste更加有用;sprintf則常用于對輸出實(shí)現(xiàn)精確的控制。
使用paste()
a <- "apple"
b <- "banana"
# 將a,b變量內(nèi)容連到一起,并用空格隔開
paste(a, b)
#> [1] "apple banana"
# 如果不想要空格,可以設(shè)定參數(shù)sep="",或使用函數(shù) paste0():
paste(a, b, sep="")
#> [1] "applebanana"
paste0(a, b)
#> [1] "applebanana"
# 用逗號加空格分開:
paste(a, b, sep=", ")
#> [1] "apple, banana"
# 設(shè)定一個(gè)字符向量
d <- c("fig", "grapefruit", "honeydew")
# 如果輸入是一個(gè)向量,輸出會(huì)將其每個(gè)元素堆疊到一起:
paste(d, collapse=", ")
#> [1] "fig, grapefruit, honeydew"
# 如果輸入是一個(gè)標(biāo)量和一個(gè)向量, 結(jié)果會(huì)將標(biāo)量與向量里每個(gè)元素放到一起
# 并返回一個(gè)向量(這是R向量化操作的循環(huán)對齊原則):
paste(a, d)
#> [1] "apple fig" "apple grapefruit" "apple honeydew"
# 使用 sep 和 collapse參數(shù):
paste(a, d, sep="-", collapse=", ")
#> [1] "apple-fig, apple-grapefruit, apple-honeydew"
使用sprintf()
另一種方式是使用sprintf函數(shù),它來自于C語言。
想要在字符串或字符變量中進(jìn)行取代操作,使用%s:
a <- "string"
sprintf("This is where a %s goes.", a)
#> [1] "This is where a string goes."
如果是整數(shù),可以使用%d或它的變體:
x <- 8
sprintf("Regular:%d", x)
#> [1] "Regular:8"
# 可以輸出到字符串,以空格開頭。
sprintf("Leading spaces:%4d", x)
#> [1] "Leading spaces: 8"
# 也可以使用0替代
sprintf("Leading zeros:%04d", x)
#> [1] "Leading zeros:0008"
對浮點(diǎn)數(shù),使用%f進(jìn)行標(biāo)準(zhǔn)釋義,而%e活著%E則代表指數(shù)。你也可以使用%g或者%G讓程序自動(dòng)幫你進(jìn)行兩種格式的轉(zhuǎn)換,這取決于你的有效位數(shù)。下面是R help頁面中關(guān)于sprintf的例子:
sprintf("%f", pi) # "3.141593"
sprintf("%.3f", pi) # "3.142"
sprintf("%1.0f", pi) # "3"
sprintf("%5.1f", pi) # " 3.1"
sprintf("%05.1f", pi) # "003.1"
sprintf("%+f", pi) # "+3.141593"
sprintf("% f", pi) # " 3.141593"
sprintf("%-10f", pi) # "3.141593 " (左對齊)
sprintf("%e", pi) #"3.141593e+00"
sprintf("%E", pi) # "3.141593E+00"
sprintf("%g", pi) # "3.14159"
sprintf("%g", 1e6 * pi) # "3.14159e+06" (指數(shù)化)
sprintf("%.9g", 1e6 * pi) # "3141592.65" ("修正")
sprintf("%G", 1e-6 * pi) # "3.14159E-06"
在%m.nf格式規(guī)范中:m代表域?qū)?,它是輸出字符串中字符的最小位?shù),可以以空格或0開頭。n代表精度,它指小數(shù)點(diǎn)后的數(shù)字位數(shù)。
其他混合操作:
x <- "string"
sprintf("Substitute in multiple strings: %s %s", x, "string2")
#> [1] "Substitute in multiple strings: string string2"
# To print a percent sign, use "%%"
sprintf("A single percent sign here %%")
#> [1] "A single percent sign here %"
注意
關(guān)于更多腳本輸出的信息可以查看this page。