【问题标题】:How to assign multiple csv files to multiple names in a loop in r?如何在r中的循环中将多个csv文件分配给多个名称?
【发布时间】:2021-07-11 07:28:40
【问题描述】:

我对 R 不是很熟悉,我正在努力为这段代码编写一个循环函数。 如您所见,只有“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)))



【问题讨论】:

    标签: r csv


    【解决方案1】:

    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 数量的增长,这很难管理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 2020-12-27
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多