Difference between revisions of "R/Cheatsheet"
Jump to navigation
Jump to search
(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....") |
|||
Line 5: | Line 5: | ||
<span class="highlight">chr</span> "2014-01-06 00:23:24" |
<span class="highlight">chr</span> "2014-01-06 00:23:24" |
||
my.date <- <span class="input">as.POSIXct</span>( my.date ) |
my.date <- <span class="input">as.POSIXct</span>( my.date ) |
||
<span class="highlight">POSIXct[1:1]</span>, 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 <tt>as.POSIXct</tt> function. |
|||
my.date <- "06/01/14 00:23:24" |
|||
str( my.date ) |
|||
<span class="highlight">chr</span> "06/01/14 00:23:24" |
|||
my.date <- <span class="input">as.POSIXct</span>( my.date, <span class="input">format="%m/%d/%y %H:%M:%S"</span> ) |
|||
<span class="highlight">POSIXct[1:1]</span>, format: "2014-01-06 00:23:24" |
<span class="highlight">POSIXct[1:1]</span>, format: "2014-01-06 00:23:24" |
||
Latest revision as of 11:31, 23 June 2014
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"