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

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)
主站蜘蛛池模板: 防城港市| 宜都市| 浦县| 尼勒克县| 宾阳县| 孟津县| 阿拉善盟| 佛教| 全椒县| 延长县| 望江县| 成都市| 昌平区| 公安县| 青川县| 峨边| 滨州市| 甘孜| 辽阳县| 阿克| 德州市| 修文县| 宁河县| 灵丘县| 宜兴市| 鹿邑县| 瓮安县| 革吉县| 六盘水市| 阳江市| 伊川县| 抚州市| 岱山县| 利辛县| 武宣县| 南安市| 铁岭县| 沿河| 宣威市| 平邑县| 三都|