Manipulate String and Datetime in R

Manipulate String with stringr

stringr is a set of simple wrappers that make R’s string functions more consistent, simpler and easier to use.

Load stringr

library(stringr)

Basic String Operators

str_count("Datayo")
#> 6

str_c("Hadley", "Wickham")
#> "HadleyWickham"

str_split("Hadley Wickham", pattern=" ")
#> "Hadley"  "Wickham"

str_sub("Hadley Wickham", start=1, end=6)
#> "Hadley"

Patern Maching

cards.list = c("4916630519923634",
  "5196175399658205",
  "4556973549398657",
  "5524728783460514",
  "4556552271734071")
visa.pattern = "^4[0-9]{12}(?:[0-9]{3})?$"
master.pattern = "^5[1-5][0-9]{14}$"

str_match(cards.list, visa.pattern)
#>     [,1]              
#> [1,] "4916630519923634"
#> [2,] NA                
#> [3,] "4556973549398657"
#> [4,] NA                
#> [5,] "4556552271734071"

str_replace(cards.list, "[0-9]{9}$", "xxxx")
#> "4916630xxxx" "5196175xxxx" "4556973xxxx"
#> "5524728xxxx" "4556552xxxx"

Piping

"Hello World"
  %>% str_sub(1, 6)
  %>% str_c("Datayo")
#> "Hello Datayo"

cards.list
  %>% str_replace(visa.pattern, "visa")
  %>% str_replace(master.pattern, "master")
#> "visa"   "master" "visa"   "master" "visa"

Manipulate Datetime with lubridate

Lubridate makes it easier to work with dates and times by providing functions to identify and parse date-time data, extract and modify components of a date-time (years, months, days, hours, minutes, and seconds), perform accurate math on date-times, handle time zones and Daylight Savings Time.

Load lubirdate

library(lubridate)

Basic Task

Get current time; add, subtract date

now()
#> "2015-04-23 10:57:20 ICT"

now() + days(1)
#> "2015-04-24 11:00:20 ICT"

now() - days(1)
#> "2015-04-22 11:00:49 ICT"

Parsing

ymd("1970-10-15")
#> "1970-10-15 UTC"

mdy("10/15/1970")
#> "1970-10-15 UTC"

dmy(15101970)
#> "1970-10-15 UTC"

References

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s