如何将DataFrame中period或period2列的数据类型转换为日期类型以用于时间序列分析
Hey there! Let's get those period columns converted to proper date types so you can jump into time series analysis without hiccups. We'll use tidyverse tools—specifically lubridate, which is made for simplifying date parsing.
First, let's start with your original data:
library(tidyverse) library(lubridate) # Your input data sales_data <- tibble( year = c(2015, 2015, 2018), period = c(201504, 201505, 201803), period2 = c("April 2015", "May 2015", "March 2018"), Sales = c(10000, 11000, 12000) )
1. Convert the period column (numeric YYYYMM format)
The period column is stored as a number (like 201504 for April 2015). First, we'll convert it to a string, then use lubridate::ym() to parse it into a date. This function automatically recognizes "YYYYMM" format and defaults to the first day of the month—perfect for time series work.
sales_data <- sales_data %>% mutate(period_date = ym(as.character(period)))
2. Convert the period2 column (month name + year string)
The period2 column uses a more readable string format ("April 2015"). For this, lubridate::my() is ideal—it directly parses month-name + year combinations without needing you to define a custom format string.
sales_data <- sales_data %>% mutate(period2_date = my(period2))
Verify the results
Let's check that our new columns are indeed Date types:
glimpse(sales_data)
You'll see output like this, confirming the date columns are correctly formatted:
Rows: 3 Columns: 6 $ year <dbl> 2015, 2015, 2018 $ period <dbl> 201504, 201505, 201803 $ period2 <chr> "April 2015", "May 2015", "March 2018" $ Sales <dbl> 10000, 11000, 12000 $ period_date <date> 2015-04-01, 2015-05-01, 2018-03-01 $ period2_date <date> 2015-04-01, 2015-05-01, 2018-03-01
A quick note: If you ever need the last day of the month instead of the first, you can adjust with ceiling_date(period_date, "month") - days(1), but the first day is standard for most time series use cases.
内容的提问来源于stack exchange,提问作者Underwood

