[R] data frame manipulation with zero rows

arnaud Gaboury arnaud.gaboury at gmail.com
Tue Jun 1 08:45:08 CEST 2010


Dear group,

Here is the kind of data.frame I obtain every day with my function :

futures <-
structure(list(DESCRIPTION = c("CORN Jul/10", "CORN Jul/10", 
"CORN Jul/10", "CORN Jul/10", "CORN Jul/10", "LIVE CATTLE Aug/10", 
"LIVE CATTLE Aug/10", "SUGAR NO.11 Jul/10", "SUGAR NO.11 Jul/10", 
"SUGAR NO.11 Jul/10", "SUGAR NO.11 Jul/10", "SUGAR NO.11 Jul/10"
), CREATED.DATE = structure(c(18403, 18406, 18406, 18406, 18406, 
18407, 18408, 18406, 18407, 18407, 18407, 18407), class = "Date"), 
    QUANTITY = c(1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1), SETTLEMENT =
c("373.2500", 
    "373.2500", "373.2500", "373.2500", "373.2500", "90.7750", 
    "90.7750", "14.9200", "14.9200", "14.9200", "14.9200", "14.9200"
    )), .Names = c("DESCRIPTION", "CREATED.DATE", "QUANTITY", 
"SETTLEMENT"), row.names = c(NA, 12L), class = "data.frame")

I need then to apply to the df this following code line :

>PosFut=ddply(futures, c("DESCRIPTION","SETTLEMENT"), summarise, POSITION=
sum(QUANTITY))[,c(1,3,2)]

It works perfectly in most of case, BUT I have a new problem: it can
sometime occurs that my df "futures" is empty, with zero rows.


futures <-
structure(list(DESCRIPTION = character(0), CREATED.DATE =
structure(numeric(0), class = "Date"), 
    QUANTITY = numeric(0), SETTLEMENT = character(0)), .Names =
c("DESCRIPTION", 
"CREATED.DATE", "QUANTITY", "SETTLEMENT"), row.names = integer(0), class =
"data.frame")

It is not the usual case, but it can happen. With this df, when I pass the
above mentione line, I get an error :

>PosFut=ddply(futures, c("DESCRIPTION","SETTLEMENT"), summarise, POSITION=
sum(QUANTITY))[,c(1,3,2)]
Error in tapply(1:nrow(data), splitv, list) : 
  arguments must have same length


How can I avoid this when my df is empty?

Any help is appreciated



More information about the R-help mailing list