跳轉到內容

R 程式設計/匯入和匯出資料

來自華夏公益教科書

資料可以以多種格式儲存。每個統計軟體包都有自己的資料格式(例如 Microsoft Excel 的 xls,Stata 的 dta,SAS 的 sas7bdat 等)。R 可以讀取幾乎所有檔案格式。我們為每種檔案型別提供了一種方法。如果以下方法都不起作用,您可以使用專門的軟體進行資料轉換,例如免費軟體OpenRefine或商業軟體 Stat Transfer。[1] 無論如何,大多數統計軟體都可以將資料匯出為 CSV(逗號分隔值)格式,並且所有軟體都可以讀取 CSV 資料。這通常是使資料對所有人可用的最佳解決方案。

圖形使用者介面

[edit | edit source]

一些 IDE 或 GUI 提供了一些一鍵式解決方案來匯入資料。

您也可以看看 speedR,這是一個圖形使用者介面,可以幫助從 Excel、OpenOfficeCalc、CSV 和其他文字檔案匯入資料。[2]

library(speedR)
speedR()

CSV (csv,txt,dat)

[edit | edit source]

您可以使用 read.table()read.csv()read.csv2() 從文字檔案(通常是 CSV)匯入資料。選項 header = TRUE 表示 CSV 檔案的第一行應解釋為變數名,選項 sep = 指定分隔符(通常是“,” 或 “;”)。

csv.get()Hmisc)是另一種選擇。

mydata <- read.table("data.txt",header=TRUE)
mydata <- read.table("data.csv", header = TRUE, sep=",")  # import from a CSV
mydata <- read.csv("data.csv", header=T)
mydata <- read.table("data.csv", header = TRUE, sep=";") 
mydata <- read.csv2("data.csv", header=T)

請注意,如果您的資料儲存在網際網路上,沒有任何問題。

df <- read.table("http://www.mywebsite.com/.../data.csv", header = TRUE, sep = ",")

預設情況下,字串會轉換為因子。如果要避免這種轉換,可以指定選項 stringsAsFactors = FALSE

您可以使用 write.table() 將資料匯出到文字檔案。

write.table(mydat,file="mydat.csv",quote=T,append=F,sep=",",eol = "\n", na = "NA", dec = ".", row.names = T,col.names = T)

對於大型 CSV 檔案,可以使用 ff 包。[3]

library("ff")
df <- read.csv.ffdf(file="large_csv_file.csv", header=TRUE, VERBOSE=TRUE, first.rows=10000, next.rows=50000)

固定寬度文字檔案

[edit | edit source]

read.fwf()write.fwf()

一些固定寬度文字檔案附帶 SAS 指令碼以匯入它們。Anthony Damico 建立了 SAScii 包來輕鬆匯入這些資料。[4]

非結構化文字檔案

[edit | edit source]

Stata (dta)

[edit | edit source]
  • 我們可以使用 foreign 包中的 read.dta() 讀取 Stata 資料,並使用 write.dta() 匯出到 Stata 資料格式。
  • 請注意,Stata 中的字串變數限制為 244 個字元。這在匯出過程中可能是一個問題。
  • 另請參閱 memisc 包中的 Stata.file()Hmisc 包中的 stata.get
> library("foreign")
> mydata <- read.dta("mydata.dta",convert.dates = TRUE, convert.factors = TRUE, convert.underscore = TRUE)
> names(mydata)
> write.dta(mydata, file = "mydata.dta")

SAS (sas7bdat)

[edit | edit source]

sas7bdat[5] 包提供了對具有sas7bdat副檔名的 SAS 資料庫的實驗性支援。但是,sas7bdat由 64 位版本的 SAS 以及執行在非 Microsoft Windows 平臺上的 SAS 生成的檔案尚不支援。

SAS (xpt)

[edit | edit source]
  • 另請參閱 Hmisc 中的 sasexport.get()sas.get()
  • 另請參閱 SASxport 包。
library("foreign")
mydata<-read.xport("SASData.xpt")
names(mydata)

SPSS (sav)

[edit | edit source]
  • read.spss()foreign)和 spss.get()Hmisc
> library("foreign")
> mydata<-read.spss("SPSSData.sav")
> names(mydata)

EViews

[edit | edit source]

hexView 包中的 readEViews() 用於 EViews 檔案。

Excel (xls,xlsx)

[edit | edit source]

從 Excel 匯入資料並不容易。解決方案取決於您的作業系統。如果以下方法都不起作用,您始終可以將每個 Excel 電子表格匯出為 CSV 格式,然後在 R 中讀取 CSV。這通常是最簡單快捷的解決方案。

XLConnect 支援讀取和寫入 xls 和 xlsx 檔案格式。由於它基於 Apache POI,因此只需要 Java 安裝,因此可以在許多平臺上執行,包括 Windows、UNIX/Linux 和 Mac。除了讀取和寫入資料之外,它還提供了一些其他功能,例如新增圖表、單元格樣式和樣式操作等等。

require("XLConnect")
wb <- loadWorkbook("myfile.xls", create = FALSE)
# Show a summary of the workbook (shows worksheets,
# defined names, hidden sheets, active sheet name, ...)
summary(wb)
# Read data from a worksheet interpreting the first row as column names
df1 <- readWorksheet(wb, sheet = "mysheet")
# Read data from a named region/range interpreting the first row as column
# names
df2 <- readNamedRegion(wb, name = "myname", header = TRUE)

RODBC 解決方案

library("RODBC")
32-bit Windows: channel <- odbcConnectExcel("Graphiques pourcent croissance.xls") # creates a connection
64-bit Windows: channel <- odbcConnectExcel2007("Graphiques pourcent croissance.xls")
sqlTables(channel) # List all the tables
effec <- sqlFetch(channel, "effec") # Read one spreadsheet as an R table
odbcClose(channel) # close the connection (don't forget)

xlsReadWrite 包(實際上,該包在 CRAN 庫中不存在,但您可以從 CRAN 存檔中下載舊版本)。

> library(xlsReadWrite)
mydat <- read.xls("myfile.xls", colNames = T, sheet = "mysheet", type = "data.frame", from = 1, checkNames = TRUE)
  • "sheet" 指定要匯入的工作表的名稱或編號。
  • "from" 指定電子表格的第一行。

gnumeric 包。[6] 該包使用一個名為 ssconvert 的外部軟體,該軟體通常與 gnumeric(Gnome Office 電子表格)一起安裝。read.gnumeric.sheet() 函式讀取 xls 和 xlsx 檔案。

library("gnumeric")
df1 <- read.gnumeric.sheet(file = "df.xls", head = TRUE, sheet.name = "Feuille1")
df2 <- read.gnumeric.sheet(file = "df.xlsx", head = TRUE, sheet.name = "Feuille1")

另請參閱 xlsx(適用於 Excel 2007 文件)和 read.xls()gdata)。

Google Spread Sheets

[edit | edit source]

您應該將電子表格公開,將其釋出為 CSV 檔案。然後,您可以使用 read.csv() 在 R 中讀取它。有關更多資訊,請參閱 Revolution 的計算部落格(link)。另請參閱 RGoogleDocslink)。

# Read from a Google SpreadSheet.
require(RCurl)
myCsv <- getURL("https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AkuuKBh0jM2TdGppUFFxcEdoUklCQlJhM2kweGpoUUE&single=true&gid=0&output=csv")
read.csv(textConnection(myCsv))

gnumeric 電子表格

[edit | edit source]

gnumeric[6]read.gnumeric.sheet() 讀取一個工作表,read.gnumeric.sheets() 讀取所有工作表並將它們儲存在一個列表中。

library("gnumeric")
df <- read.gnumeric.sheet(file = "df.gnumeric", head = TRUE, sheet.name = "df.csv")
View(df)
df <- read.gnumeric.sheets(file = "df.gnumeric", head = TRUE)
View(df$df.csv)

OpenOffice 和 LibreOffice (ods)

[edit | edit source]

readODS 不需要外部依賴,使其跨平臺。

library("readODS")
df=read.ods("df.ods")

speedR 是另一個選擇。

library("speedR")
df <- speedR.importany(file = "df.ods")

請注意,您也可以使用 speedR 圖形使用者介面 (speedR()),它將返回用於複製的命令列。

library("speedR")
speedR()

JSON (JavaScript 物件表示法) 是一種網際網路上非常常見的格式。rjson 庫使從 json 格式匯入資料變得容易[7]

# json.txt : a text file including data in the JSON format
library("rjson")
df <- fromJSON(paste(readLines("json.txt"), collapse=""))

使用以下方法可以輕鬆地將列表或資料框匯出到 JSON 格式:toJSON()函式 

# df : a data frame
library("rjson")
json <- toJSON(df)

有時 JSON 資料可能更復雜,具有巢狀陣列等結構。在這種情況下,您可能會發現使用線上轉換器(如 json-csv.com)將檔案轉換為 CSV 更有用。然後,根據 上面的 CSV 指令 匯入結果資料。

dBase (dbf)

[編輯 | 編輯原始碼]

foreign 包中的 read.dbf()

library("foreign")
df  <- read.dbf("file.dbf")
str(df)

分層資料格式 (hdf5)

[編輯 | 編輯原始碼]

hdf5 資料可以使用 hdf5 包讀取[8]

DICOM 和 NIfTI

[編輯 | 編輯原始碼]
  • 參見統計軟體雜誌中的“在 R 中使用 {DICOM} 和 {NIfTI} 資料標準工作”[9]
  • R 資料手冊[10]
  • Paul Murrell 的資料技術簡介[11]

參考文獻

[編輯 | 編輯原始碼]
  1. Stat Transfer
  2. speedR
  3. "在 R 中開啟大型 CSV 檔案". 檢索於 2013 年 3 月 7 日. {{cite web}}: 未知引數 |site= 被忽略 (幫助)
  4. David Smith. "將具有 SAS 指令的公共資料匯入 R". Revolution Analytics. 檢索於 2013 年 2 月 1 日.
  5. sas7bdat
  6. a b 此命令已在 Ubuntu 10.10 和 R 2.11.1 上測試
  7. http://cran.r-project.org/web/packages/rjson/index.html
  8. http://cran.r-project.org/web/packages/hdf5/index.html
  9. Brandon Whitcher, Volker J. Schmid, Andrew Thorton “在 R 中使用 {DICOM} 和 {NIfTI} 資料標準工作”,統計軟體雜誌 第 44 卷 第 6 期 2011 年 10 月,連結
  10. R 資料手冊
  11. Paul Murrell 資料技術簡介
上一個:資料管理 索引 下一個:圖形
華夏公益教科書