官术网_书友最值得收藏!

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.

  1. First, determine the current directory with getwd, and use list.files to check where the file is, as follows:
    > getwd()
    > list.files('./')
    
  2. 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)
    
  3. Next, filter data by selecting the first six rows with column Date, Open, High, Low, and Close:
    > subset_data <- stock_data[1:6, c("Date", "Open", "High", "Low", "Close")]
    
  4. Examine the first six rows of loaded data with the head function:
    > head(stock_data)
    
  5. 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)
主站蜘蛛池模板: 句容市| 盘锦市| 社会| 花莲市| 仁布县| 含山县| 昌黎县| 开平市| 洛浦县| 富民县| 长丰县| 潮州市| 康保县| 安国市| 安陆市| 昌黎县| 杨浦区| 黄陵县| 昔阳县| 绵阳市| 宁武县| 米林县| 兴海县| 泸定县| 龙泉市| 方山县| 固阳县| 尼勒克县| 永丰县| 台州市| 九寨沟县| 长白| 长治市| 南木林县| 大足县| 楚雄市| 洮南市| 丰原市| 临沂市| 桃园县| 上高县|