R data.table:对文件夹中的所有.csv文件使用fread,跳过每个文件的最后一行 [英] R data.table: using fread on all .csv files in folder skipping the last line of each

查看:206
本文介绍了R data.table:对文件夹中的所有.csv文件使用fread,跳过每个文件的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用fread读取数百个.csv文件并将其另存为一个数据表。每个.csv的基本结构都相同。有标题信息需要跳过(使用skip =可以轻松实现)。我在跳过每个.csv文件的最后一行时遇到困难。每个.csv文件的行数都不同。

I have hundreds of .csv files I need to read in using fread and save as one data table. The basic structure is the same for each .csv. There is header info that needs to be skipped (easy using skip = ). I am having difficulty with skipping the last line of each .csv file. Each .csv file has a different number of rows.

如果Test文件夹中只有一个文件,则此脚本会完美跳过第一行(使用skip =),然后最后一行(使用nrows =):

If I have only one file in the Test folder, this script perfectly skips the first rows (using skip = ) and the last row (using nrows = ):

file <- list.files("Q:/Test/", full.names=TRUE)
all <- fread(file, skip = 7, select = c(1:7,9),
             nrows = length(readLines(file))-9)

在测试文件夹中保存多个文件时,这是我尝试的代码:

When saving multiple files in the Test folder, this is the code I tried:

file <- list.files("Q:/Test/", full.names=TRUE)
L <- lapply(file, fread, skip = 7, select = c(1:7,9),
        nrows = length(readLines(file))-9)
dt <- rbindlist(L)

它不会创建L并给我这个错误:

It doesn't create L and gives me this error:

Error in file(con, "r") : invalid 'description' argument

关于每个.csv具有不同数量的.csv时如何跳过每个.csv最后一行的任何想法

Any ideas on how to skip the last row of each .csv when each .csv has a different number of rows?

我正在使用data.table版本1.9.6。谢谢。

I am using data.table version 1.9.6. Thanks.

推荐答案

有点晚了,但这对我有用:

It's a bit late, but here's what worked for me:

library(data.table)

fnames <- dir("path", pattern = "csv")

read_data <- function(z){
  dat <- fread(z, skip = 1, select = 1)
  return(dat[1:(nrow(dat)-1),])
}

datalist <- lapply(fnames, read_data)

bigdata <- rbindlist(datalist, use.names = TRUE)

此处路径指的是您要查找的目录。我假设所有读取文件的名称都是相似的,否则,您可以始终使用名称 bigdata 定义新名称。 c $ c>。希望这可以帮助!

Here path refers to the directory that you're looking into. I'm assuming that the names are similar for all read files, if not, you can always define a new name for bigdata using names. Hope this helps!

这篇关于R data.table:对文件夹中的所有.csv文件使用fread,跳过每个文件的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆