R/Cheatsheet

From braindump
Revision as of 13:11, 22 June 2014 by Uroesch (talk | contribs) (Created page with "=== 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 <tt>as.POSIXct</tt> function. my....")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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"

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"