You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中编写自定义函数合并列生成yyyy/mm/dd格式日期列?

Combine Year/Month/Day into a yyyy/mm/dd Date Column (Custom Function)

Hey there! Since you're new to writing custom functions in R, let's break this down step by step—you've already got the tidyverse set up, so we'll lean into those tools to make this straightforward.

First, let's recap your existing dataset code for reference:

library(tidyverse)
df <- tibble(Year = rep(2020, times = 5), Month = seq(1:5), DayOfMonth = seq(1:5), DayOfWeek = seq(1:5))

Custom Function Walkthrough

We'll build a function that takes your dataset, pads single-digit months/days with leading zeros, then combines them into a properly formatted date string (and optionally a true Date type column, which is useful for date-based operations later).

Here's the function:

create_formatted_date <- function(data, year_col = "Year", month_col = "Month", day_col = "DayOfMonth") {
  # Use tidyverse functions to transform the data
  data %>%
    mutate(
      # Pad month/day to 2 digits (so 1 becomes "01")
      padded_month = str_pad({{month_col}}, width = 2, side = "left", pad = "0"),
      padded_day = str_pad({{day_col}}, width = 2, side = "left", pad = "0"),
      # Create yyyy/mm/dd string
      date_string = str_c({{year_col}}, padded_month, padded_day, sep = "/"),
      # Optional: Convert string to a true Date type (great for sorting/calculations)
      date = as.Date(date_string, format = "%Y/%m/%d")
    ) %>%
    # Remove temporary padding columns if you don't need them
    select(-padded_month, -padded_day)
}

Key Explanations:

  • {{col_name}}: This is tidyverse's "tidy evaluation" syntax—it lets the function recognize column names from your dataset, even if you pass them as arguments.
  • str_pad(): From the stringr package (part of tidyverse), this ensures single-digit months/days get a leading zero (critical for the yyyy/mm/dd format).
  • str_c(): Glues the year, padded month, and padded day together with / separators.
  • as.Date(): Converts the string into a proper Date object—this is optional, but highly recommended if you plan to do things like filter by date, calculate time differences, or sort chronologically.

How to Use the Function

Simply pass your dataset to the function, and it will return the original data with your new date columns added:

# Apply the function to your df
df_with_date <- create_formatted_date(df)

# View the result
df_with_date

Sample Output

You'll get a tibble that looks like this:

# A tibble: 5 × 6
   Year Month DayOfMonth DayOfWeek date_string  date      
  <dbl> <int>      <int>     <int> <chr>        <date>    
1  2020     1          1         1 2020/01/01   2020-01-01
2  2020     2          2         2 2020/02/02   2020-02-02
3  2020     3          3         3 2020/03/03   2020-03-03
4  2020     4          4         4 2020/04/04   2020-04-04
5  2020     5          5         5 2020/05/05   2020-05-05

Quick Alternative (No Custom Function)

If you don't need to reuse this logic for other datasets, you can do this directly with dplyr without a function:

df %>%
  mutate(
    date = as.Date(str_c(Year, str_pad(Month, 2, "left", "0"), str_pad(DayOfMonth, 2, "left", "0")), format = "%Y%m%d") %>%
      format("%Y/%m/%d")
  )

But the custom function is great if you need to apply this same formatting to multiple datasets later!

内容的提问来源于stack exchange,提问作者kiwi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:28:12