Frage

I am trying to take a data frame and expand it into panel data inside a function.

require(lubridate)
require(plyr)

df <- data.frame(group = seq(1, 10))

f <- function(df, sdate, edate) {
  df <- ddply(df, .(group), transform, year = year(seq(ymd(sdate), ymd(edate), by = "year")))
  return(df)
}

f(df, "1945-1-1", "2013-1-1")

This throws the error: Error in lapply(list(...), .num_to_date) (from #3) : object 'sdate' not found

It seems that sdate and edate are passed correctly and have the correct type in the function.

War es hilfreich?

Lösung 2

That's the problem of scoping. Here is a workaround:

> f <- function(df, sdate, edate) {
+   df <- ddply(df, .(group), 
+               function(x) data.frame(year = year(seq(ymd(sdate), ymd(edate), by = "year"))))
+   return(df)
+ }
> 
> head(f(df, "1945-1-1", "2013-1-1"))
  group year
1     1 1945
2     1 1946
3     1 1947
4     1 1948
5     1 1949
6     1 1950

Andere Tipps

Another alternative is to to use do.call with a call to construct the call in an environment where "sdate" and "edate" are visible:

f <- function(df, sdate, edate) {
  df <- do.call("ddply",list(df, "group", transform, 
                       year = call("year",x= seq(ymd(sdate), 
                                          to = ymd(edate), by = "year"))))
  return(df)
}

f(df, "1945-1-1", "2013-1-1")
    group year
1       1 1945
2       1 1946
3       1 1947
4       1 1948
5       1 1949
6       1 1950
7       1 1951
8       1 1952

EDIT

The plyr-style solution(Simpler)

You should use plyr::here :

This function captures the current context, making it easier to use **ply with functions that do special evaluation and need access to the environment where ddply was called from.

f <- function(df, sdate, edate) {
   ddply(df, .(group), plyr::here(transform), 
                             year = year(seq(ymd(sdate), ymd(edate), by = "year")))
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top