Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: xtable and dates

Tags:

I have the following data:

transaction <- c(1,2,3); date <- c("2010-01-31","2010-02-28","2010-03-31"); type <- c("debit", "debit", "credit"); amount <- c(-500, -1000.97, 12500.81); oldbalance <- c(5000, 4500, 17000.81) evolution <- data.frame(transaction, date, type, amount, oldbalance, row.names=transaction, stringsAsFactors=FALSE); evolution <- transform(evolution, newbalance = oldbalance + amount); evolution 

Running

> library(xtable) > xtable(evolution) 

works fine. But if I add the line

evolution$date <- as.Date(evolution$date, "%Y-%m-%d"); 

to give

transaction <- c(1,2,3); date <- c("2010-01-31","2010-02-28","2010-03-31"); type <- c("debit", "debit", "credit"); amount <- c(-500, -1000.97, 12500.81); oldbalance <- c(5000, 4500, 17000.81) evolution <- data.frame(transaction, date, type, amount, oldbalance, row.names=transaction, stringsAsFactors=FALSE); evolution$date <- as.Date(evolution$date, "%Y-%m-%d"); evolution <- transform(evolution, newbalance = oldbalance + amount); evolution 

then running xtable gives

xtable(evolution) Error in Math.Date(x + ifelse(x == 0, 1, 0)) : abs not defined for Date objects

But it can be useful to use xtable in such a case to do some filtering of dates

evolution$date <- as.Date(evolution$date, "%Y-%m-%d") startdate <-as.Date("2010-02-01"); enddate <-as.Date("2010-03-30"); newdate <-evolution[which (evolution$date >= startdate & evolution$date <= enddate),] newdate   > newdate   transaction       date  type   amount oldbalance newbalance 2           2 2010-02-28 debit -1000.97       4500    3499.03 > xtable(newdate) Error in Math.Date(x + ifelse(x == 0, 1, 0)) :   abs not defined for Date objects 
like image 228
yCalleecharan Avatar asked Dec 28 '11 06:12

yCalleecharan


1 Answers

This is arguably a bug in xtable - you may want to report it to the maintainer.

A temporary work-around is to call as.character() on the classes that xtable misinterprets (apart from "Date" I can think of "POSIXt" but there may be others), e.g.:

xtable <- function(x, ...) {    for (i in which(sapply(x, function(y) !all(is.na(match(c("POSIXt","Date"),class(y))))))) x[[i]] <- as.character(x[[i]])    xtable::xtable(x, ...) } 
like image 170
Simon Urbanek Avatar answered Oct 19 '22 03:10

Simon Urbanek