将一行代码变成一个函数,dplyr,R

问题描述 投票:0回答:1

我需要帮助将以下工作代码行转换为一个函数,该函数采用数据帧、列名称(例如年份)和行号(例如 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"))
}

r dplyr
1个回答
0
投票
library(tidyverse)
library(admiral)
library(lubridate)

impute_year <- function(date_df, year_col, row_num) {
  as.integer(as_date(admiral::impute_dtc_dt(dtc = date_df[[year_col]][row_num], highest_imputation = "M", date_imputation = "06-15")) - as_date("1899-12-30"))
}

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"
)

# Test the function
impute_year(date_df, "year", 4) # Returns 36525

在原始代码中,date_df$year[4] 行直接访问 date_df 数据框中年份列的第 4 个元素。 在函数中,我们需要使用 [[ 运算符按名称访问列 (date_df[[year_col]][row_num])。这 !!最初尝试中使用的运算符在这里不是必需的。 其余的函数逻辑保持不变,使用 admiral::impute_dtc_dt() 估算日期,然后计算自“1899-12-30”以来的天数。 该函数现在采用三个参数: date_df:输入数据帧 year_col:包含年份数据的列的名称 row_num:从中提取年份数据的行号 它返回与原始一行代码相同的整数结果。

© www.soinside.com 2019 - 2024. All rights reserved.