在R中导入月度时间序列数据集并转换为ts对象的方法求助
Hey there! Let's work through your two time series data problems one by one—they're common hurdles, so I've got clear, actionable steps for you.
Your data is structured with years as rows and months as columns, plus sales values with thousand separators. If you import it without adjustments, R might mislabel columns as X1/X2 or treat numeric values as text. Here's how to fix that:
Step 1: Read the data with proper settings
Useread.table(orread.csvfor CSV files) to keep month names as column headers and years as row names. For your sample data, you can use thetextparameter directly; replace it with a file path for your actual dataset:# Read sample data (swap text with file = "your_data.csv" for real files) myData <- read.table( text = "JAN FEB MAR APR MAY JUNE 2016 4457 4,105 4,276 4712 5,116 4,512 2017 4,222 5,432 4,816 5,018 4,497 4,603 2018 4,355 4,972 4,868 4,665 4,735 4,926", header = TRUE, # Use the first row as month column names row.names = 1, # Use the first column as year row names stringsAsFactors = FALSE # Prevent R from converting values to factors )Step 2: Clean numeric values
The commas in sales numbers will be read as text, so we’ll remove them and convert columns to numeric:# Remove thousand separators and convert to numeric myData[] <- lapply(myData, function(x) as.numeric(gsub(",", "", x)))Now your data frame will have proper month column names and numeric sales values—no random
X1/X2labels.
Using as.ts(myData) directly creates a multi-variate time series (mts) because R treats each month column as a separate series, and defaults to a frequency of 1 (since it has no context about your monthly data). Here's how to create a single, monthly time series:
Step 1: Reshape data into a chronological vector
We need to stack data in time order: 2016 Jan → 2016 Feb → ... → 2018 Jun. Extract each year's monthly data row-wise and combine into one vector:# Combine yearly monthly data into a single time-ordered vector sales_vector <- unlist(apply(myData, 1, c), use.names = FALSE)Step 2: Create the ts object with correct frequency
Use thets()function to define the start date and monthly frequency (12):# Create monthly time series object data.ts <- ts( sales_vector, start = c(2016, 1), # Start at January 2016 frequency = 12 # 12 observations per year (monthly) )Verify with
str(data.ts)—you’ll see a singletsobject with frequency 12, not anmtsor matrix.
内容的提问来源于stack exchange,提问作者Unknown

