在R语言中读取股票市场JSON数据:保留时间戳与数值的方法求助
Hey there! I’ve run into this exact issue before—when importing stock data, it’s easy to end up with just numeric values if the timestamp isn’t properly parsed. Let’s walk through a few reliable ways to keep both your timestamps and stock values intact.
1. Use quantmod for Direct Stock Data Pulls (Most Common)
If you’re fetching data directly from sources like Yahoo Finance, quantmod is your go-to package—it automatically preserves timestamps as part of an xts (extensible time series) object.
# Install and load the package first if you haven't install.packages("quantmod") library(quantmod) # Grab data for a stock (e.g., Apple ticker: AAPL) getSymbols("AAPL", src = "yahoo") # Check the output—timestamps are stored as rownames of the xts object head(AAPL)
If you prefer a standard data frame with an explicit timestamp column, convert it like this:
# Convert xts object to data frame and add timestamp column aapl_df <- as.data.frame(AAPL) aapl_df$timestamp <- index(AAPL) # Extract timestamps from the xts index # Reorder columns to put timestamp first (optional but cleaner) aapl_df <- aapl_df[, c("timestamp", names(aapl_df)[-ncol(aapl_df)])] head(aapl_df)
2. Importing Local CSV/TSV Files
If you’re working with a local data file (e.g., downloaded stock data), the key is to make sure R recognizes the timestamp column as a date/datetime type, not plain text.
Base R Method
# Replace "your_stock_data.csv" with your file path stock_data <- read.csv( "your_stock_data.csv", stringsAsFactors = FALSE, colClasses = c("POSIXct", rep("numeric", 5)) # Adjust numeric count to match your columns ) # Verify the timestamp column is correctly parsed str(stock_data)
Tidyverse (readr) Method (Easier for Auto-Parsing)
The readr package (part of tidyverse) automatically detects date/datetime columns, which saves you manual work:
install.packages("tidyverse") library(tidyverse) stock_data <- read_csv("your_stock_data.csv") # Check column types to confirm timestamp is parsed correctly glimpse(stock_data)
Handling Non-Standard Timestamp Formats
If your timestamps use a non-standard format (e.g., dd/mm/yyyy instead of yyyy-mm-dd), use the lubridate package to parse them explicitly:
library(lubridate) stock_data$timestamp <- dmy(stock_data$timestamp) # For day-month-year format # Use ymd() for year-month-day, mdy() for month-day-year, etc.
Quick Troubleshooting Tip
If you’re still losing timestamps, double-check:
- Your input file actually includes a timestamp column (it sounds obvious, but it’s easy to miss!)
- You’re not accidentally dropping the column during import (e.g., using
select()too early) - The timestamp format is consistent across all rows (inconsistent formats can cause parsing failures)
内容的提问来源于stack exchange,提问作者Akshay Nagpal

