使用R语言quantmod库读取CSV时如何保留字符型行名
Got it, let's tackle this issue— I’ve dealt with this exact problem when working with quantmod and date-formatted row names in CSVs. Here’s why it’s happening and how to fix it:
Why Your Row Names Are Turning to 1, 2, 3...
The most common culprit is that quantmod’s default CSV-reading functions (like read.zoo or getSymbols with src="csv") aren’t recognizing your date strings as the index/row names of your dataset. Instead, they’re auto-generating integer row IDs (starting at 1) and treating your dates as just another data column (or ignoring them entirely).
Step-by-Step Fixes
Option 1: Read with read.csv First, Then Convert to xts
This is the most straightforward approach for preserving row names:
- Use base R’s
read.csvto load the data, explicitly telling it to use the first column as row names:# Load the CSV, keep first column as row names raw_data <- read.csv("your_data.csv", row.names = 1, stringsAsFactors = FALSE) - Convert the data frame to an xts object (quantmod’s preferred format) while parsing the row names as dates:
library(quantmod) # Convert row names to Date objects and set as the xts index quantmod_data <- as.xts(raw_data, order.by = as.Date(rownames(raw_data)))
Option 2: Use read.zoo Directly with Proper Arguments
Since quantmod relies on zoo/xts, you can use read.zoo directly and specify how to handle your date row names:
library(quantmod) # Read CSV, use first column as row names, parse them as dates zoo_data <- read.zoo( "your_data.csv", header = TRUE, # If your CSV has column headers sep = ",", # Match your CSV's delimiter row.names = 1, # Use first column as row names FUN = as.Date # Convert row names to Date objects ) # Convert to xts for quantmod compatibility quantmod_data <- as.xts(zoo_data)
Option 3: Fix getSymbols for CSV Reads
If you’re using getSymbols to load your CSV, specify the index column explicitly:
library(quantmod) # Tell getSymbols to use the first column as the date index getSymbols( "your_data.csv", src = "csv", index.column = 1, # Set first column as the time index header = TRUE, sep = "," )
Key Notes
- Double-check your CSV structure: Make sure your date strings are in the first column of the file. If the column has a header (like "Date"), use
index.column = "Date"instead of1in the above functions. - For non-standard date formats (e.g.,
08/05/1970instead of1970-05-08), adjust theFUNargument to parse correctly:# Example for DD/MM/YYYY format FUN = function(x) as.Date(x, format = "%d/%m/%Y")
Give these methods a shot, and your original date row names should stay intact instead of being replaced with numeric IDs!
内容的提问来源于stack exchange,提问作者HonnSolo

