[R] When customizing last line, the code stops working
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Nov 3 14:41:26 CET 2016
On 03/11/2016 8:29 AM, Frank S. wrote:
> Dear all,
>
>
> The function I present works perfectly when I run it as written (that is, leaving NEW LINE as commented). However, when
>
> I try to run the same function via this mentioned line (and therefore commenting LAST LINE) R gives an error message:
> Error in FUN(X[[i]], ...) : object 'dt_sp_1' not found. I do not understand why I don't get the same result.
You aren't specifying the "envir" argument to "get", so it defaults to
the environment from which you called get, and that's the evaluation
frame of lapply() (or maybe of do.call()).
Write the last line as
union <- do.call(rbind, lapply(paste0("dt_sp_", 1:length(sp)), get, envir = environment()))
and it works.
Duncan Murdoch
>
>
> Thanks in advance for any help!
>
>
> Frank S.
>
>
> all.sp <- function(age.u, open, close) {
>
> require(data.table)
> dt <- data.table( id = c(rep(1, 2), 2:4, rep(5, 2)),
> sex = as.factor(rep(c(0, 1), c(3, 4))),
> fborn = as.Date(c("1935-07-25", "1935-07-25", "1939-07-23", "1943-10-05",
> "1944-01-01", "1944-09-07", "1944-09-07")) )
>
> sp <- seq(open, close, by = "year")
> dt_sp <- list()
> for (i in 1:length(sp)) {
> vp <- as.POSIXlt(c(as.Date("1000-01-01"), sp))
> vp$year <- vp$year - age.u
> dt.cut <- as.numeric(cut(x = as.POSIXlt(dt$fborn), breaks = vp, right = TRUE, include.lowest = TRUE))
> dt_sp[i] <- split(dt, factor(dt.cut, i))
> dt_sp[[i]] <- data.table(dt_sp[[i]])[, entry_sp := sp[i]]
> assign(paste0("dt_sp_", 1:length(sp))[i], dt_sp[[i]])
> }
>
> union <- rbind(dt_sp_1, dt_sp_2, dt_sp_3, dt_sp_4) # LAST LINE: IT WORKS
>
>
> # I TRY TO CUSTOMIZE LAST LINE, BUT THEN CODE STOPS WORKING
> # union <- do.call(rbind, lapply(paste0("dt_sp_", 1:length(sp)), get)) # NEW LINE
> }
>
> # Example:
> result <- all.sp(age.u = 65, open = as.Date("2007-01-01"), close = as.Date("2010-05-01"))
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list