Search code examples
rdplyr

turn line of code into a function, dplyr, R


I need assistance to convert the following working line of code into a function that takes a dataframe, a column name (e.g., year), and a row number (e.g., 4) then returns the same integer result as the one line of code. My attempt below is not working.

library(tidyverse)
library(admiral)
library(lubridate)

date_df <- tribble(
  ~id, ~year,
  1, "2020-01-01",
  2, "2021-06-15",
  3, "2023-12-31",
  4, "1999",
  5, "1978",
  6, "2001-10-07",
)

# This function works, gives result as: 36525
as.integer(as_date(admiral::impute_dtc_dt(dtc = date_df$year[4], highest_imputation = "M", date_imputation = "06-15")) - as_date("1899-12-30")) # Result: 36525


# This doesn't work: My attempt at turning above into a function that takes a dataframe, a column name (e.g., year), and a row number (e.g., 4( then returns the same integer result
impute_year <- function(date_df, year, rownum) {
  as.integer(as_date(admiral::impute_dtc_dt(dtc = date_df$!!year[!!rownum], highest_imputation = "M", date_imputation = "06-15")) - as_date("1899-12-30"))
}


Solution

  • Why do you think that you need both year and rownum as parameters? If I'm understanding your goal right, these two alternatives should work:

    impute_year <- function(date_df, chosen_year) {
      as.integer(as_date(admiral::impute_dtc_dt(dtc = date_df$year[which(date_df$year == chosen_year)], highest_imputation = "M", date_imputation = "06-15")) - as_date("1899-12-30"))
    }
    
    impute_year(date_df, "1999")
    
    
    impute_year <- function(date_df, rownum) {
      as.integer(as_date(admiral::impute_dtc_dt(dtc = date_df$year[rownum], highest_imputation = "M", date_imputation = "06-15")) - as_date("1899-12-30"))
    }
    
    impute_year(date_df, 4)
    

    Hope that helps!