[R] Row median of Date class variables in a data frame
Gabor Grothendieck
ggrothendieck at myway.com
Thu Feb 24 05:14:48 CET 2005
Stephen D. Weigand <weigand.stephen <at> charter.net> writes:
:
: I am trying to calculate the median of each row of a
: data frame where the data frame consist of
: columns of class Date.
:
: Below are my test data and best attempt at using apply.
: I didn't see a solution via Google or the Baron search
: site.
:
: I'd be grateful for any suggestions or solutions.
: I'm using R 2.0.0 on Mac OS X.
:
: Thank you,
:
: Stephen Weigand
:
: ### Test data
:
: date1 <- c(1000, 2000, 3000,4000)
: date2 <- date1 + 100
: date3 <- date2 + 100
:
: class(date1) <- class(date2) <- class(date3) <- "Date"
:
: test <- data.frame(date1, date2, date3)
:
: print(test)
:
: ### create a function for apply()
: medDate <- function(x){
: obj <- unclass(unlist(x))
: med <- median(obj, na.rm = TRUE)
: med
: class(med) <- "Date"
: med
: }
:
: medDate(test$date1) # works
: medDate(test[1,]) # works
:
: apply(test, 1, medDate) # gives error: 'need numeric data'
: apply(test, 2, medDate) # gives error: 'need numeric data'
:
Try this:
library(zoo)
as.Date(apply(data.matrix(test), 1, median)) # ignore warning
The only reason you need zoo is that it supplies as.Date methods
which convert numerics and integers to Date.
More information about the R-help
mailing list