Professional Documents
Culture Documents
鍵盤輸入
1
scan("", what = double(), n = -1, sep = "", quiet = FALSE)
file = "":由鍵盤輸入
what = double():輸入之資料型式,預設為 numeric,可為 ""、integer、logical、list 等
n = -1:輸入 items 個數,預設為無限大,直到輸入 enter 鍵為止
sep = "":除了 enter 之外,可以用空白鍵分隔 items
quiet = FALSE:最後呈現輸入多少 items
x <- scan("", n = 3, sep = " ", quiet = TRUE)
y <- scan("", what = "", sep = ",", quiet = TRUE) # 輸入內容轉成字串
z <- scan("", what = list(name = "", pay = integer(0), sex = ""))
字串處理
查尋字串內容
grep(pattern, x) 查尋字串
pattern:查尋項目,可為字串或正則表達式 (regular expression)
x:被查尋項目
s1 <- replicate(5, paste(sample(letters[1:10], 8, replace = TRUE), collapse = ""))
grep("a", s1)
grepl(pattern, x) 查尋是否含有特定字串
grep("a", s1) grepl("a", s1)
擷取字串內容
substr(x, start, stop) 取出指定位置的字串
x:character vector
start/stop:開始/結束字元數
s2 <- paste(LETTERS, collapse = "") s3 <- paste(letters, collapse = "")
s4 <- paste(0:9, collapse = "")
substr(s2, 3, 10) substr(c(s2, s3, s4), 3, 10) substr(c(s2, s3, s4), 1:3, 10:8)
substr(s4, 5, 12)
substring(x, first) 取出指定位置到結束的字串
first:開始字元數
substring(s2, 5) substring(c(s2, s3, s4), 5) substring(c(s2, s3, s4), c(10, 15, 5))
substring(s4, 12)
strtrim(x, width) (從開頭) 取出指定長度的字串
strtrim(s2, 5) strtrim(c(s2, s3, s4), 5) strtrim(c(s2, s3, s4), 5:7)
strtrim(s4, 12)
strsplit(x, split) 根據字元分割字串
split:分隔字元
回傳值為 list 型式
strsplit(s1[1], "a") strsplit(s1, "a") strsplit(s1, letters[1:5])
替換字串
2
sub(old, new, x) 將 x 中的 old 字串替換成 new 字串
old 可為正則表達式
只執行一次替換
sub("a", "#A#", s1[1]) sub("a", "#A#", s1)
gsub(old, new, x)
替換所有符合條件
gsub("a", "#A#", s1[1]) gsub("a", "#A#", s1)