- R for Data Science Cookbook
- Yu Wei Chiu (David Chiu)
- 381字
- 2021-07-14 10:51:25
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("Date", "Open", "High", "Low", "Close")]
- Examine the first six rows of loaded data with the
head
function:> head(stock_data)
- As the file to be loaded is in CSV format, you can also use
read.csv
to read the file:> stock_data2 <- read.csv('snp500.csv', header=TRUE) > head(stock_data2)
How it works…
By following the previous recipe, you should now have Yahoo Finance data downloaded in the current directory. As the downloaded file is organized in a table, you can use the read.table
function to read data from the file into an R data frame.
As the downloaded data is separated with a comma and contains a column header, you can set header
equal to TRUE
and ',
' as the field separator in function parameters. After you have read snp500.csv
into the stock_data
data frame, you can then select the first six rows from the data for further examination with the head
function.
Similar to the read.table
function, you can also use read.csv
to read the text file. The only difference between read.csv
and read.table
is that read.csv
uses commas as the default separator to read the file, while read.table
uses white space as the default separator. You can also use the head
function to examine the loaded data frame.
There's more…
In the previous section, we demonstrated how to use RCurl
to obtain Wi-Fi hotspot data from the NYC open data site. As the downloaded data is in character vector, we can use read.csv
to read text into an R session by setting text equal to character vector rows
in the function argument:
> wifi_hotspot <- read.csv(text = rows)
- iOS Game Programming Cookbook
- Flink SQL與DataStream入門、進階與實戰
- Java高手真經(高級編程卷):Java Web高級開發技術
- VMware虛擬化技術
- Active Directory with PowerShell
- Python機器學習算法: 原理、實現與案例
- Oracle GoldenGate 12c Implementer's Guide
- C++20高級編程
- Java零基礎實戰
- Scala Data Analysis Cookbook
- Couchbase Essentials
- Building Serverless Web Applications
- Python青少年趣味編程
- Android應用開發實戰(第2版)
- Java EE Web應用開發基礎