R讀取檔案

32 views
Skip to first unread message

李宜臻

unread,
Dec 7, 2022, 10:57:10 PM12/7/22
to R軟體使用者論壇
我想以迴圈的方式讀取資料夾裡的檔案:

place<-c('keelung','taipei','newtaipei','taoyuan','hsinchu','miaoli','taichung','changhua','yunlin','chiayi','tainan','kaohsiung','pingtung','yilan','hualien')
datatype<-c('_juniorhigh')
filetype<-c('.csv')
name1=c(paste0(place,datatype))
name2=c(paste0(place,datatype,filetype))
for (x in name1){
  x=fread(paste0(x,'.csv'),header = TRUE)
}

但只會讀取一份檔案(keelung_juniorhigh.csv),而且檔案名稱甚至是x,沒有如我預期的顯示keelung_juniorhigh,請問應該如何修改呢?

WEPA ^_^

unread,
Dec 8, 2022, 11:16:52 AM12/8/22
to R軟體使用者論壇
Hi Joanne

參考以下程式:
 
# 問題: 大量檔案之讀取
# 日期: 2022.12.8
# 參考資料: https://github.com/rwepa/DataDemo/blob/master/ai_using_python_and_r/ai_using_python_and_r_part2_r.R#L1534

library(data.table)

# 建立篩選縣市
place <- c('keelung','taipei','newtaipei','taoyuan','hsinchu','miaoli','taichung','changhua','yunlin','chiayi','tainan','kaohsiung','pingtung','yilan','hualien')

# 模擬15個縣市的CSV檔案
for (i in 1:length(place)) {
  mytmp <- data.frame(id=i, place=place[i])
  write.table(x=mytmp, file=paste0(place[i], '_juniorhigh', '.csv'), sep = ",", row.names = FALSE)
}

# 方法1.使用 for loop-顯示資料
for (x in place){
  tmp <- paste0(x, '_juniorhigh', '.csv')
  x <- fread(file=tmp, sep=",")
  print(x)
}

# 方法2.使用 for loop-將匯入資料合併為資料框
mydf <- data.frame() # 建立空白資料框

for (x in place){
  tmp <- paste0(x, '_juniorhigh', '.csv')
  x <- fread(file=tmp, sep=",")
  mydf <- rbind(mydf, x)
}
str(mydf) # 15*2
# Classes ‘data.table’ and 'data.frame':    15 obs. of  2 variables:
#  $ id   : int  1 2 3 4 5 6 7 8 9 10 ...
#  $ place: chr  "keelung" "taipei" "newtaipei" "taoyuan" ...
#  - attr(*, ".internal.selfref")=<externalptr>

# 方法3.使用 lapply

# getwd() 可以修改為實際工作目錄
# pattern 可以使用"正規表示式". 輸入 ?regex 查詢線上說明.
files <- dir(getwd(), pattern="*_juniorhigh.csv", recursive=TRUE, full.names=TRUE)
tables <- lapply(files, fread, sep=",") # list
mydf1 <- do.call(rbind, tables) # data.frame
mydf1
# end


joanne1...@gmail.com 在 2022年12月8日 星期四上午11:57:10 [UTC+8] 的信中寫道:
Reply all
Reply to author
Forward
0 new messages