通过合并csv文件向创建的数据框添加新列

问题描述 投票:0回答:1

希望有人可以帮助我解决这个问题。基本上,我有几个csv文件,我想合并所有文件以创建一个数据框。每个csv文件都有多个行(csv文件的主要部分),然后有一些空行,然后是有关特定文件的一些信息。例如,csv文件1:

a b c d 
1 2 4 3
4 3 4 2


p 2
t 3

csv文件2:

a b c d 
0 2 1 8
3 4 1 2


p 4
t 6

我已经能够加入所有csv文件的主要部分。为此,我刚刚创建了一个函数。在此特定示例中,我只需要前三行,因此:

multmerge=function(mypath) {
  filenames=list.files(path=mypath, full.names=TRUE)
  datalist= lapply(filenames, function (x) read.csv(file=x, header=TRUE, 
  nrows=3))
  Reduce(function(x,y) merge(x,y, all = TRUE), datalist)}

  full_data <- multmerge(mypath)

结果是这样的:

a b c d 
1 2 4 3
4 3 4 2
0 2 1 8
3 4 1 2

但是,我希望dataframe full_data包含每个csv文件的信息部分中的变量,所以最后我会得到这样的内容:

a b c d p t
1 2 4 3 2 3
4 3 4 2 2 3
0 2 1 8 4 6
3 4 1 2 4 6

任何提示?

谢谢!

r dataframe read.csv
1个回答
0
投票

这是我的data.table解决方案。

为了保持动态,它会读取每个文件几次。在处理大文件(或大量文件)时,这可能会大大降低速度。但是据我所知,这是使用data.table::fread()跳过文件底部的唯一方法。此解决方案的额外好处是您的文件可以具有任意行数。该代码仅去除最后四个(两个空白,并带有p / t值的行)。

我的样本数据存在两个文件,./csv1.csv./csv2.csv,其中包含问题的样本数据。

下面的代码中会发生什么:-建立您要阅读的文件列表-在自定义函数中使用data.table::fread()读取文件:_-确定文件中要读取的行数;_-首先读取每个文件的最后四行,但最后四行除外;_-然后读取每个文件的最后两行;_-以我们想要的格式组合这两个结果。-将列表绑定到一个数据表。

#get a list of files you want to read
filelist <- list.files( path = "./", pattern = "^csv[12]\\.csv", full.names = TRUE )

#read the files to a list, using a custom function
l <- lapply( filelist, function(x) {
  #get the length of the file first, by reading in the file 
  # sep = "" is for faster reading of the file
  length_file <- nrow( fread(x, sep = "", header = TRUE ) )
  #use data.table::fread to read in the file EXCEPT the four last lines
  file_content <- data.table::fread( x, nrows = length_file - 4 , fill = TRUE )
  #use data.table::fread to read in the file ONLY the last two lines
  file_tail    <- data.table::fread( x, skip = length_file - 2 , fill = TRUE )
  #build final output
  output <- file_content[, `:=`( p = file_tail[ V1 == "p", V2 ],
                                 t = file_tail[ V1 == "t", V2 ] )]
})

# [[1]]
#    a b c d p t
# 1: 1 2 4 3 2 3
# 2: 4 3 4 2 2 3
# 
# [[2]]
#    a b c d p t
# 1: 0 2 1 8 4 6
# 2: 3 4 1 2 4 6

#use data.table::rbindlist() to bind the list to a single data.table
data.table::rbindlist( l )

#    a b c d p t
# 1: 1 2 4 3 2 3
# 2: 4 3 4 2 2 3
# 3: 0 2 1 8 4 6
# 4: 3 4 1 2 4 6
© www.soinside.com 2019 - 2024. All rights reserved.