Мне нужна помощь, чтобы преобразовать следующую рабочую строку кода в функцию, которая принимает фрейм данных, имя столбца (например, год) и номер строки (например, 4), а затем возвращает тот же целочисленный результат, что и одна строка кода. Моя попытка ниже не работает.
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"))
}
Как вы думаете, почему вам нужны оба параметра: year
и rownum
?
Если я правильно понимаю вашу цель, эти две альтернативы должны работать:
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)
Надеюсь, это поможет!