Created
April 17, 2012 14:37
-
-
Save geofferyzh/2406383 to your computer and use it in GitHub Desktop.
RinAction - R Functions - Character Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
########################################### | |
## Character Function ## | |
########################################### | |
# Number of characters | |
x <- c("ab", "cde", "fghij") | |
a <- length(x) | |
b <- nchar(x[3]) # returns 5 | |
# substring | |
x <- "abcdef" | |
a <-substr(x,2,4) # returns "bcd" | |
substr(x,2,4) <- "22222" # returns "a222ef" | |
# search | |
grep("A", c("b","A","c"), fixed=TRUE, ignore.case=FALSE) # returns index | |
# replace | |
sub("\\s",".","Hello There") # replace whitespace with . | |
# split - | |
y <- strsplit("abc", "") # returns a 1-component 3-element list containing "a" "b" "c" | |
y | |
unlist(y)[2] # returns "b" | |
sapply(y,"[",2) # returns "b" | |
# concatenate strings | |
paste("x", 1:3, sep="") | |
paste("TOday is", date()) | |
# Uppercase | |
toupper("abc") | |
# Lowercase | |
tolower("ABC") | |
############################# | |
### Escape Characters ####### | |
############################# | |
# \n -- new line | |
# \s -- white space | |
# \t -- tab | |
# \' -- single quote | |
# \b -- backspoace | |
name <- "Bob" | |
cat("Hello", name, "\b.\n","Isn\'t R", "\t", "GREAT?\n") | |
# Note: When cat concatenates objects for output, it separates each by a space. | |
# That’s why you include the backspace (\b) escape character before the period. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment