Home > OS >  Pass a function to a function map and dplyr
Pass a function to a function map and dplyr

Time:10-15

I have made my own function:

n_hires <- function(data, year) {
  data %>%
    filter(year(DateofHire) == year) %>%
    nrow()
}

that I want to pass to another function I have written:

df_count <- function(data, f) {
  map_dbl(years, ~ .f(data = .data, year = .x)) %>%
    setNames(years) %>%
    as.data.frame() %>%
    setNames("n") %>%
    rownames_to_column("Year")
}

When I run the function:

df_count(data = df, .f = n_hires)

It returns:

> df_count(data = df, .f = n_hires)
  Error in df_count(data = df, .f = n_hires) : 
  unused argument (.f = n_hires)

How do I pass a function to a function?

CodePudding user response:

The function provided in df_count didn't show an input for 'years'. If we add, it may work (not tested). Also, the f can be directed passed and there is no .f

df_count <- function(data, years, f) {
    map_dbl(years, ~ f(data = data, year = .x)) %>% 
              setNames(years) %>%
             as.data.frame() %>%   
             setNames("n") %>%   
     rownames_to_column("Year")
 } 

CodePudding user response:

I think you are overcomplicating this. Creating n_hires function to filter for a particular year and count the number of rows and then create df_count to run a loop to count the number of rows for every year. Instead of this you can calculate number of rows for each year directly.

library(dplyr)
library(lubridate)

data %>% count(year = year(DateofHire))

If you are interested in specific years only you can filter them.

data %>% count(year = year(DateofHire)) %>% filter(year %in% years)
  • Related