将多个函数应用于R中的单个输入

时间:2014-02-14 22:29:01

标签: r plyr

我有一系列用于计算日期的函数 - 例如。

m() # return the date of the first day of the month
s() # return the date of the first day of the season 
ly() # return the matching date for last year (not on 365 day calendar 

我需要做以下事情:

    today <- Sys.Date() 
    monthStart <- m(today)  
    seasonStart <-s(today)  
    matchLy <- ly(today)  
    ly.monthStart <- m(ly(today))  
    ly.seasonStart  <-s(ly(today)) 

然而,上面看起来相当笨重而且非R。是否有一个衬垫可以将这些函数应用于输入(今天)并解压缩到全局变量?

3 个答案:

答案 0 :(得分:0)

虽然不完全是单行,但在使用您的函数创建列表后,这是一个单一的声明:

library(functional)
today <- Sys.Date() 
funs <- list(mStart=m, seasStart=s, matchLy=ly, 
  ly.ms=Compose(m, ly), ly.ss=Compose(s, ly))   # notice Compose

现在运行:

list2env(envir=globalenv(), lapply(funs, function(x) x(today)))

那就是说,我不确定这比你之前使用过的块好多少。主要问题是您希望分配到全球环境,因为这需要您开发唯一的名称。如果您只是想将这些函数序列应用于许多日期并将结果存储在列表或数据框架或其他类似的框架中,那么这将变得更加清晰。

答案 1 :(得分:0)

您可以在以下的静脉中编写自定义函数:

map <- function(x, ...) {
  functions <- list(...)
  res <- list()
  for (i in 1:length(functions)) 
    res[[i]] <- functions[[i]](x)
  names(res) <- names(functions)
  return(res)
}

然后将几个函数应用于一个数据:

res <- map(Sys.Date(), monthStart=m, 
                       seasonStart=s, 
                       matchLy=ly)

将其推入环境:

list2env(res, envir=globalenv())

答案 2 :(得分:0)

这样的事情会起作用吗?

library(lubridate)
today <- Sys.time()
funs <- c("day", "month", "year")
sapply(funs, do.call, list(today))