R/Cheatsheet

From braindump
Jump to navigation Jump to search

Convert to timestamp

Given a string in the form of YYYY-MM-DD HH:MM:SS for example in a data frame one an easily convert it with the as.POSIXct function.

my.date <- "2014-01-06 00:23:24" 
str( my.date ) 
chr "2014-01-06 00:23:24"
my.date <- as.POSIXct( my.date ) 
POSIXct[1:1], format: "2014-01-06 00:23:24"

Convert to timestamp from non ISO formats

If the date string is not in the form of YYYY-MM-DD HH:MM:SS one needs to add the format=to the as.POSIXct function.

my.date <- "06/01/14 00:23:24" 
str( my.date ) 
chr "06/01/14 00:23:24"
my.date <- as.POSIXct( my.date, format="%m/%d/%y %H:%M:%S" ) 
POSIXct[1:1], format: "2014-01-06 00:23:24"

Changing a factored value

Adding a new valued to a factor requires a bit of preparation or it will go wrong.

my.factor <- factor(  c( "foo", "bar", "foo" ) )
levels( my.factor ) 
[1] "bar" "foo"
levels( my.factor ) <- c( levels( my.factor ), "batz" ) 
my.factor[ my.factor == "bar" ] <- "batz"

Removing unused levels from factors

levels( my.factor )
[1] "bar"  "foo"  "batz"
my.factor <- factor( my.factor)
levels( my.factor )
[1] "bar"  "batz"