欲買桂花同載酒,終不似,少年遊。
阿新 • • 發佈:2019-02-11
這兩個函式返回向量水平的匹配結果,不涉及匹配字串的詳細位置資訊。
grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE) grepl(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
雖然引數看起差不多,但是返回的結果不一樣。下來例子列出C:\windows目錄下的所有檔案,然後用grep和grepl查詢exe檔案:
files <- list.files("c:/windows") grep("\\.exe$", files)
## [1] 8 28 30 35 36 58 69 99 100 102 111 112 115 117
grepl("\\.exe$", files)
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE ## [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [23] FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE ## [34] FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [45] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [56] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [67] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [78] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [89] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE ## [100] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [111] TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE
grep僅返回匹配項的下標,而grepl返回所有的查詢結果,並用邏輯向量表示有沒有找到匹配。兩者的結果用於提取資料子集的結果都一樣:
files[grep("\\.exe$", files)]
## [1] "bfsvc.exe" "explorer.exe" "fveupdate.exe" "HelpPane.exe" ## [5] "hh.exe" "notepad.exe" "regedit.exe" "twunk_16.exe" ## [9] "twunk_32.exe" "uninst.exe" "winhelp.exe" "winhlp32.exe" ## [13] "write.exe" "xinstaller.exe"
files[grepl("\\.exe$", files)]
## [1] "bfsvc.exe" "explorer.exe" "fveupdate.exe" "HelpPane.exe" ## [5] "hh.exe" "notepad.exe" "regedit.exe" "twunk_16.exe" ## [9] "twunk_32.exe" "uninst.exe" "winhelp.exe" "winhlp32.exe" ## [13] "write.exe" "xinstaller.exe"