Reading and writing CSV files
In the previous recipe, we downloaded the historical S&P 500 market index from Yahoo Finance. We can now read the data into an R session for further examination and manipulation. In this recipe, we demonstrate how to read a file with an R function.
Getting ready
In this recipe, you need to have followed the previous recipe by downloading the S&P 500 market index text file to the current directory.
How to do it…
Please perform the following steps to read text data from the CSV file.
- First, determine the current directory with
getwd
, and uselist.files
to check where the file is, as follows:> getwd() > list.files('./')
- You can then use the
read.table
function to read data by specifying the comma as the separator:> stock_data <- read.table('snp500.csv', sep=',' , header=TRUE)
- Next, filter data by selecting the first six rows with column
Date
,Open
,High
,Low
, andClose
:> subset_data <- stock_data[1:6, c...