簡體   English   中英

如何在 r 的循環中將多個 csv 文件分配給多個名稱?

[英]How to assign multiple csv files to multiple names in a loop in r?

我對 R 並不完全熟悉,我正在努力為這段代碼編寫一個循環 function 。 如您所見,只有“indice”旁邊的數字發生了變化,但我不知道如何進行循環。 我總共有 5 個文件,雖然不多,但我不想一遍又一遍地寫同一行。 非常感謝你們,祝你們有美好的一天。

indice = read.csv("C:/Users/huonn/Desktop/Thèse recherche/data/CAC40.csv");
indice2 = read.csv("C:/Users/huonn/Desktop/Thèse recherche/data/DAX.csv");
indice3 = read.csv("C:/Users/huonn/Desktop/Thèse recherche/data/DJIA.csv");


colnames(indice)
names(indice)[names(indice) == "ï..Date"] <- "Date"
indice$Date <- as.Date(indice$Date,
                       format = "%d/%m/%Y")
indice$Dernier <- as.numeric(gsub(",", ".", gsub("\\.", "", indice$Dernier)))

colnames(indice2)
names(indice2)[names(indice2) == "ï..Date"] <- "Date"
indice2$Date <- as.Date(indice2$Date,
                       format = "%d/%m/%Y")
indice2$Dernier <- as.numeric(gsub(",", ".", gsub("\\.", "", indice2$Dernier)))

colnames(indice3)
names(indice3)[names(indice3) == "ï..Date"] <- "Date"
indice3$Date <- as.Date(indice3$Date,
                        format = "%d/%m/%Y")
indice3$Dernier <- as.numeric(gsub(",", ".", gsub("\\.", "", indice3$Dernier)))



lapply在這里對你有幫助。

filenames <- list.files('C:/Users/huonn/Desktop/Thèse recherche/data/', full.names = TRUE, pattern = '\\.csv$')

lapply(filenames, function(x) {
  indice <- read.csv(x)
  names(indice)[names(indice) == "ï..Date"] <- "Date"
  indice$Date <- as.Date(indice$Date,format = "%d/%m/%Y")
  indice$Dernier <- as.numeric(gsub(",", ".", gsub("\\.", "", indice$Dernier)))
  indice
}) -> result

result中包含數據框列表。 最好將數據保存在列表中,而不是在全局環境中創建多個對象(如indiceindice2等),隨着 csv 數量的增長,這很難管理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM