Function Description
substr(x, start=n1, stop=n2) Extract or replace substrings in a character vector.
x <- "abcdef"
substr(x, 2, 4) is "bcd"
substr(x, 2, 4) <- "22222" is "a222ef"
grep(pattern, x , ignore.case=FALSE, fixed=FALSE) Search for pattern in x. If fixed =FALSE then pattern is a regular expression. If fixed=TRUE then pattern is a text string. Returns matching indices.
grep("A", c("b","A","c"), fixed=TRUE) returns 2
sub(pattern, replacement, x, ignore.case =FALSE, fixed=FALSE) Find pattern in x and replace with replacement text. If fixed=FALSE then pattern is a regular expression.
If fixed = T then pattern is a text string.
sub("\\s",".","Hello There") returns "Hello.There"
strsplit(x, split) Split the elements of character vector x at split.
strsplit("abc", "") returns 3 element vector "a","b","c"
paste(…, sep="") Concatenate strings after using sep string to seperate them.
paste("x",1:3,sep="") returns c("x1","x2" "x3")
paste("x",1:3,sep="M") returns c("xM1","xM2" "xM3")
paste("Today is", date())
toupper(x) Uppercase
tolower(x) Lowercase
sprintf(fmt, …)
字串連接
tmp = paste("GAD", "AB", sep = ",")
tmp
[1] "GAD,AB"
子字串
str("abcdef", 2, 4)
[1] "bcd"
substring("abcdef", 1:6, 1:6)
[1] "a" "b" "c" "d" "e" "f"
## strsplit is more efficient …
substr(rep("abcdef", 4), 1:4, 4:5)
[1] "abcd" "bcde" "cd" "de"
x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
substr(x, 2, 5)
[1] "sfef" "wert" "uiop" "" "tuff"
substring(x, 2, 4:6)
[1] "sfe" "wert" "uiop[" "" "tuff"
substring(x, 2) <- c("..", "+++")
x
[1] "a..ef" "q+++ty" "y..op[" "b"
[5] "s..ff.blah.yech"
x <- "1234567890"
substr(x, 3, 3)
[1] "3"
substr(x, 5, 7)
[1] "567"
substr(x, 4, 4) <- "A"
x
[1] "123A567890"
substr(x, 2, 4) <- "TTF"
x
[1] "1TTF567890"
substr(x, 9, 12) <- "ABCD"
x
[1] "1TTF5678AB"
substring(x, 5)
[1] "5678AB"
substring(x, 5) <- "…"
x
[1] "1TTF…8AB"
參考
- http://stackoverflow.com/questions/7201341/how-can-2-strings-be-concatenated-in-r
- http://stat.ethz.ch/R-manual/R-devel/library/base/html/substr.html
Post preview:
Close preview