R語言之——字串處理函數,字串函數

來源:互聯網
上載者:User

R語言之——字串處理函數,字串函數
nchar

取字元數量的函數
length與nchar不同,length是取向量的長度

# nchar表示字串中的字元的個數nchar("abcd")[1] 4# length表示向量中元素的個數length("abcd")[1] 1length(c("hello", "world"))[1] 2
paste和paste0

字串粘合函數
paste在不指定分割符的情況下,預設分割符是空格
paste0在不指定分割符的情況下,預設分割符是空

# 預設以空格隔開paste("Hello","world")[1] "Hello world"# 沒有空格paste0("Hello","world")[1] "Helloworld"# 指定分割符paste("abc", "efg", "hijk", sep = "-")[1] "abc-efg-hijk"# 分別對向量的每一個元素進行串連paste0("A", 1:6, sep = "")[1] "A1" "A2" "A3" "A4" "A5" "A6"# collapse參數:每一個元素操作之後,再把向量的每一個元素進行串連paste0("A", 1:6, sep = "",collapse = "-")[1] "A1-A2-A3-A4-A5-A6"
substr

字串截取函數

substr(x = "hello", start = 1, stop = 2)[1] "he"
strsplit

字串的分割函數,可以指定分割符,產生一個list

strsplit("abc", split = "")[[1]][1] "a" "b" "c"

如果要對一個向量使用該函數,需要注意。

# 分割向量的每一個元素,並取分割後的第一個元素unlist(lapply(X = c("abc", "bcd", "dfafadf"), FUN = function(x) {return(strsplit(x, split = "")[[1]][1])}))[1] "a" "b" "d"
gsub和sub

字串替換
gsub替換匹配到的全部
sub 替換匹配到的第一個

# 將b替換為Bgsub(pattern = "b", replacement = "B", x = "baby")[1] "BaBy"gsub(pattern = "b", replacement = "B", x = c("abcb", "boy", "baby"))[1] "aBcB" "Boy"  "BaBy"# 只替換第一個bsub(pattern = "b", replacement = "B", x = "baby")[1] "Baby"sub(pattern = "b", replacement = "B", x = c("abcb", "baby"))[1] "aBcb" "Baby"
grep和grepl

字串匹配
grep函數返回的是索引值
grepl函數返回的是邏輯值

# 返回匹配到的元素的索引grep(pattern = "boy", x = c("abcb", "boy", "baby"))[1] 2# 返回邏輯值grepl(pattern = "boy", x = c("abcb", "boy", "baby"))[1] FALSE  TRUE FALSE
match && pmatch &&charmatch

1、match
Usage
match(x, table, nomatch = NA_integer_, incomparables = NULL)
x %in% table

參數:
x: vector or NULL: the values to be matched. Long vectors are supported.

table : vector or NULL: the values to be matched against. Long vectors are not supported. (被匹配的值)

nomatch: the value to be returned in the case when no match is found. Note that it is coerced to integer. (沒有match上的返回的值)

incomparables : a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. For historical reasons, FALSE is equivalent to NULL. (不同來匹配的值)

match函數類似與 %in%,不同的是match返回的是索引,而%in%返回的是邏輯值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.