Skip to content

speeding up expandYearlyCosts #5

Description

@TellAnAx

Hi there,
when working with the invacost package, I noticed that the expandYearlyCosts() function is very slow. I ran a benchmark and processing the data according to the example you provide takes about 45 s on my machine.

From what I can see, the reason is that the following code is inefficient:

return(
    dplyr::bind_rows(
      lapply(costdb$Cost_ID, function(x, costdb.,
                                      start,
                                      end) { 
        years <- costdb.[which(costdb.$Cost_ID == x), start]:
          costdb.[which(costdb.$Cost_ID == x), end]
        return(data.frame(Impact_year = years,
                          costdb.[which(costdb.$Cost_ID == x), ][
                            rep(seq_len(nrow(costdb.[costdb.$Cost_ID == x, ])), 
                                each = length(years)), ]))
      }, costdb. = costdb, start = startcolumn, end = endcolumn)
    )
  )

The costdb. is subsetted by Cost_ID, then expanded, the resulting dataframe saved as element of a list and then the entire list is merged rowwise. This process could be done much more efficiently by using some tidyverse functions. I would suggest an update. 😃

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions