簡體   English   中英

如何讀取R中的每個.csv文件並將其導出為單個大文件

[英]How to read every .csv file in R and export them into single large file

嗨,我有以下格式的數據

101,20130826T155649
------------------------------------------------------------------------
3,1,round-0,10552,180,yellow
12002,1,round-1,19502,150,yellow
22452,1,round-2,28957,130,yellow,30457,160,brake,31457,170,red
38657,1,round-3,46662,160,yellow,47912,185,red

我一直在閱讀它們,並通過此代碼對其進行清潔/格式化

b <- read.table("sid-101-20130826T155649.csv", sep = ',', fill=TRUE, col.names=paste("V", 1:18,sep="") )
b$id<- b[1,1]
b<-b[-1,]
b<-b[-1,]
b$yellow<-B$V6

依此類推,大約有300個這樣的文件,理想情況下,它們都將在沒有前兩行的情況下進行編譯,因為第一行只是id,我創建了一個單獨的列來標識這些數據。 有誰知道如何快速讀取這些表並清理和格式化我想要的方式,然后將它們編譯成大文件並導出?

您可以使用lapply讀取所有文件,清理並格式化它們,並將結果數據幀存儲在列表中。 然后使用do.call將所有數據幀組合為單個大數據幀。

# Get vector of files names to read
files.to.load = list.files(pattern="csv$")

# Read the files
df.list = lapply(files.to.load, function(file) {
   df = read.table(file, sep = ',', fill=TRUE, col.names=paste("V", 1:18,sep=""))
   ... # Cleaning and formatting code goes here
   df$file.name = file  # In case you need to know which file each row came from
   return(df)
})

# Combine into a single data frame
df.combined = do.call(rbind, df.list)

暫無
暫無

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

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