如何在R语言(quantmod包)中将xts对象转换为data.frame
Hey folks, I recently needed to convert an xts object to a data frame in R and worked out a straightforward solution. Let me share a complete, working example using historical S&P 500 data to walk you through the process:
1. Load Required Packages
We’ll use quantmod to fetch financial data (which comes as an xts object by default) and tidyverse for easy data manipulation:
library(quantmod) library(tidyverse)
2. Fetch S&P 500 Data (Creates an xts Object)
Let’s pull historical S&P 500 data from Yahoo Finance. The getSymbols() function automatically creates an xts object named GSPC in your environment (the return value is just the string name of the object, so assigning it to SP500 is optional unless you need to reference the symbol name later):
getSymbols("^GSPC", src = "yahoo", from = as.Date("2002-01-01"), to = as.Date("2017-12-31"))
If you check the first few rows of the xts object, you’ll notice the date is stored as the row index, not a regular column:
head(GSPC)
Output:
GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted 2002-01-02 1148.08 1154.67 1136.23 1154.67 1171000000 1154.67 2002-01-03 1154.67 1165.27 1154.67 1165.27 1259700000 1165.27 ...
3. Convert xts to Data Frame
To turn this into a standard data frame with the date as a proper, usable column, we’ll first convert the xts object to a data frame with as.data.frame(), then use rownames_to_column() (from the tibble package, included in tidyverse) to move the row index into a dedicated Date column:
# Convert xts to data frame and add Date column GSPC_df <- as.data.frame(GSPC) %>% rownames_to_column(var = "Date") # Check the converted data frame head(GSPC_df)
Output:
Date GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted 1 2002-01-02 1148.08 1154.67 1136.23 1154.67 1171000000 1154.67 2 2002-01-03 1154.67 1165.27 1154.67 1165.27 1259700000 1165.27 ...
That’s all there is to it! Now you have a fully functional data frame with all your original time series data, plus a proper Date column that’s easy to use for filtering, plotting, or further analysis.
内容的提问来源于stack exchange,提问作者GuilhermeAgsouza

