Liz's Blog

就是要學R #5:Import & Export 匯入匯出篇(csv & excel)

| Comments

本來以為匯入匯出篇應該會蠻簡單的,結果大多是在解決系統上的問題。

Udemy
課程名稱:Data Science and Machine Learning Bootcamp with R
講師:Jose Portilla

1.CSV(讀取read、存檔write)

test <- read.csv('test.csv')           #需注意檔案路徑
str(test)
colnames(test)

df <- data.frame(test)
head(df)

help(read.csv)                         

read.table('test.csv')
read.table(file = 'test.csv', sep = ',')

write.csv(df, file = "test1.csv")
write.csv(df, file = "foo.csv",row.names = FALSE)

fread()也有和read.table相同的作用,但如果輸入fread(),出現沒有這個函式的話,可以先安裝data.table這個package。

install.packages(data.table)
library(data.table)

fread(test.csv)

2.讀取Excel檔案
如果沒有readxl,先安裝readxl,有的話直接載入package即可。

install.packages('readxl',repos="http://cran.rstudio.com/")
library(readxl)

excel_sheets('test.xlsx')                      #會出現sheets的列表
df <- read_excel('test.xlsx',sheet='Sheet1')   #呼叫特定sheet

head(df)
sum(df['Dose'])
str(df)
summary(df)

如果要把好幾個sheet都放入一個list,則用lapply()。

entire_workbook <- lapply(excel_sheets("test.xlsx"), 
                      read_excel, 
                      path = "test.xlsx")

entire_workbook

3.存檔Excel檔案

install.packages('xlsx',repos="http://cran.rstudio.com/")
library(rJava)
library(xlsxjars)
library(xlsx)

df <- data.frame(matrix(1:8))
write.xlsx(df, "test2.xlsx")
read_excel('test2.xlsx')

如果沒有rJava和xlsxjars,記得要先安裝package。

install.packages(rJava)
install.packages(xlsxjars)

如果有像我遇到以下問題:
Error : .onLoad failed in loadNamespace() for 'rJava', details:
call: dyn.load(file, DLLpath = DLLpath, ...)
error: 無法載入共享物件 '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/rJava/libs/rJava.so' :
dlopen(/Library/Frameworks/R.framework/Versions/3.3/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
Referenced from: /Library/Frameworks/R.framework/Versions/3.3/Resources/library/rJava/libs/rJava.so
Reason: image not found
錯誤: package or namespace load failed for ‘rJava’

可以參考這篇除錯
我是先在終端機輸入:sudo R CMD javareconf
R console輸入install.packages("rJava", type = "source")
接著在終端機輸入:sudo ln -f -s $(/usr/libexec/java_home)/jre/lib/server/libjvm.dylib /usr/local/lib
接著再重新安裝rJava,並載入library(rJava)應該就可以。

Comments

comments powered by Disqus