Copy and paste the following code to your R Studio platform or R version:

# Dates
# install.packages(“lubridate”)
library(lubridate)
Sys.time()
class(Sys.time())

d1 <- “2014-11-28”
d1
d1 <- ymd(d1)
class(d1)
d1 <- ymd(d1, tz = “UTC”)
class(d1)
day(d1)
month(d1)
week(d1)
weekdays(d1)

d2 <- “2015-12-13”
d2 <- ymd(d2, tz = “UTC”)
d <- d2 – d1
d
difftime(d2, d1, unit = “week”)
difftime(d2, d1, unit = “hours”)

# String Manipulations
paste(“txt1”, “txt2”)
paste(“txt1”, “txt2”, “txt3”, sep = “——“)

paste(c(“a”, “b”), c(“c”, “d”), sep = “–“)
paste(c(“a”, “b”), c(“c”, “d”), sep = “–“, collapse = “&”)

# Common string operations
# install.packages(“stringr”)
library(stringr)
a <- “The Lord of the Rings and Harry Potter are the most fascinating tales ever told in English. 12.3.”
b <- ” @r_programming ”

str_count(b)
str_count(a)

str_to_upper(a)
str_to_title(a)

# Split a string into sentences or words
str_split(a, ” “)
unlist(str_split(a, ” “))

substr(b, 2, str_count(b))

# Grab the words from a sentence
word(a, c(2:5))

str_detect(b, “[:punct:]”)
str_detect(b, “@”)
str_detect(b, “@”)

# We can replace characters in a string
str_replace_all(a, “t”, “L”)
# Here, for instance, we replace all lower case t with upper case L
# Or
str_replace_all(b, “[:punct:]”, “”)
# Or
str_replace_all(a, “[0-9]”, “Hi!”)

# Let’s trim some whitespace
str_trim(b, side = “both”)

# —————————- A Mini Challenge —————————— #
# Extract the names of the two books from the string a and put it in title case
a <- “The Lord of the Rings and Harry Potter are the most fascinating tales ever told in English”
y <- word(a, c(1:8))
y

LOTR <- paste(y[1:5])
LOTR
LOTR <- paste(y[1:5], collapse = ” “)
LOTR
str_to_title(LOTR)

HR <- paste(y[7:8], collapse = ” “)
HR
str_to_title(HR)

Posted by Dimitris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s