代码之家  ›  专栏  ›  技术社区  ›  Mus mzuba

如何从数百个.csv文件的特定单元格中提取值?

  •  0
  • Mus mzuba  · 技术社区  · 6 年前

    .csv B2 如果使用电子表格软件打开)。

    每个文件都是单个日期的摘录,并相应地命名(即。 extract_2017-11-01.csv , extract_2018-04-05

    我知道我可以这样做来迭代文件(如果我错了,请纠正我,或者如果有更好的方法,请告诉我):

    path <- "~/csv_files"
    
    out.file <- ""
    
    file.names <- dir(path, pattern =".csv")
    
    for(i in 1:length(file.names)){
      file <- read.table(file.names[i], header = TRUE, sep = ",")
      out.file <- rbind(out.file, file)
    }
    

    我想在最后添加一些东西,创建一个由两列组成的数据框:第一列将显示日期(理想情况下,这将取自文件名),第二列将保存单元格中的值 .

    我该怎么做?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Mus mzuba    6 年前

    这样,您可以在导入时仅选择第二行和第二列:

    extract_2018_11_26 <- read.table("csv_files/extract_2018-11-26.csv", 
                                     sep=";", header = T, nrows=1, colClasses = c("NULL", NA, "NULL"))
    

    nrows=1 意味着我们只读取第一行(除了 header 在里面 colClasses 你保密 "NULL" NA 如果你想保留它。

    下面是您的代码, gsub() 用于查找模式并将其替换为字符串:

    out.file <- data.frame()
    for(i in 1:length(file.names)){
      file <- read.table(file.names[i], 
                         sep=";", header = T, nrows=1, colClasses = c("NULL", NA,"NULL"))
    
      date <- gsub("csv_files/extract_|.csv", "",x=file.names[i]) # extracts the date from the file name
      out.file <- rbind(out.file, data.frame(date, col=file[, 1]))
    }
    
    out.file
    #         date col
    # 1 2018-11-26   2
    # 2 2018-11-27   2
    

    这两个 .csv

    #first file, name: extract_2018-11-26.csv
      col1 col2 col3
    1    1    2    3
    2    4    5    6
    #second file, name: extract_2018-11-27.csv
      col1 col2 col3
    1    1    2    3
    2    4    5    6
    
        2
  •  0
  •   Wimpel    6 年前

    数据表法

    #build a list with csv files you want to load
    files <- list.files( path = "yourpath", pattern = ".*.csv$", full.names = TRUE )
    
    library(data.table)
    #get value from second row (skip = 1) , second column ( select = 2 ) from each csv, using `data.table::fread`... 
    #bind the list together using `data.table::rbindlist`
    rbindlist( lapply( files, fread, nrows = 1, skip = 1, select = 2 ) )