R language--string processing function

Source: Internet
Author: User
Tags lua

NChar

A function that takes a number of characters
Length is different from nchar.

# nchar表示字符串中的字符的个数nchar("abcd")[1] 4# length表示向量中元素的个数length("abcd")[1] 1length(c("hello", "world"))[1] 2
Paste

String glue function
Paste the default delimiter is a space without specifying a separator
Paste0 The default delimiter is empty without specifying a separator

# Separated by a space by defaultPaste"Hello","World")[1]"Hello World"# no spacesPASTE0 ("Hello","World")[1]"Helloworld"# Specify a separatorPaste"ABC","EFG","Hijk", Sep ="-")[1]"Abc-efg-hijk"# Connect each element of a vector separatelyPASTE0 ("A",1:6, Sep ="")[1]"A1" "A2" "A3" "A4" "A5" "A6"# collapse Parameters: After each element operation, connect each element of the vectorPASTE0 ("A",1:6, Sep ="", collapse ="-")[1]"A1-a2-a3-a4-a5-a6"
Substr

String intercept function

"hello"1stop2)[1"he"
Strsplit

The split function of the string, you can specify the delimiter, generate a list

strsplit("abc""")[[1]][1"a""b""c"

If you want to use this function on a vector, you need to be aware of it.

# 分割向量的每一个元素,并取分割后的第一个元素unlist(lapply(X = c("abc""bcd""dfafadf"function(x) {return"")[[1]][1])}))[1"a""b""d"
Gsub and Sub

String substitution
gsub Replace all matches to
The sub replaces the first one that matches the

# Replace B with BGsub (pattern ="B", replacement ="B", x ="Baby")[1]"BaBy"Gsub (pattern ="B", replacement ="B", x = C ("ABCB","Boy.","Baby"))[1]"ABCB" "Boy."  "BaBy"# Replace only the first BSub (pattern ="B", replacement ="B", x ="Baby")[1]"Baby"Sub (pattern ="B", replacement ="B", x = C ("ABCB","Baby"))[1]"ABCB" "Baby"
grep and Grepl

String match
the grep function returns the index value
The GREPL function returns a logical value

# 返回匹配到的元素的索引grep(pattern = "boy", x = c("abcb", "boy", "baby"))[1] 2# 返回逻辑值grepl(pattern = "boy", x = c("abcb", "boy", "baby"))[1] FALSE  TRUE FALSE

R language--string processing function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.