簡體   English   中英

將多個 CSV 文件讀取到單獨的數據幀中

[英]Read multiple CSV files into separate data frames

Suppose we have files file1.csv , file2.csv , ... , and file100.csv in directory C:\R\Data and we want to read them all into separate data frames (eg file1 , file2 , ... , and文件 100 )。

這樣做的原因是,盡管它們具有相似的名稱,但它們具有不同的文件結構,因此將它們放在列表中並不是那么有用。

我可以使用lapply但它返回一個包含 100 個數據幀的列表。 相反,我希望在全球環境中使用這些數據框。

如何將多個文件直接讀取到全局環境中? 或者,或者,如何將數據框列表的內容解壓縮到其中?

快速草稿,未經測試:

  1. 使用list.files() dir()動態生成文件列表。

  2. 這將返回一個向量,只需沿着向量在for循環中運行即可。

  3. 讀取第i個文件,然后使用assign()將內容放入新變量file_i中

那應該為您解決問題。

謝謝大家的答復。

為了完整起見,這是我加載任何數量(制表符)分隔文件的最終答案,在這種情況下,該文件包含6列數據,其中第1列是字符,第2列是因數,其余數字:

##Read files named xyz1111.csv, xyz2222.csv, etc.
filenames <- list.files(path="../Data/original_data",
    pattern="xyz+.*csv")

##Create list of data frame names without the ".csv" part 
names <-substr(filenames,1,7)

###Load all files
for(i in names){
    filepath <- file.path("../Data/original_data/",paste(i,".csv",sep=""))
    assign(i, read.delim(filepath,
    colClasses=c("character","factor",rep("numeric",4)),
    sep = "\t"))
}

結合使用assign和一個包含所需數據框名稱的字符變量。

for(i in 1:100)
{
   oname = paste("file", i, sep="")
   assign(oname, read.csv(paste(oname, ".txt", sep="")))
}

這是一種僅使用lapply解壓data.frames列表的方法

filenames <- list.files(path="../Data/original_data",
                        pattern="xyz+.*csv")

filelist <- lappy(filenames, read.csv)

#if necessary, assign names to data.frames
names(filelist) <- c("one","two","three")

#note the invisible function keeps lapply from spitting out the data.frames to the console

invisible(lapply(names(filelist), function(x) assign(x,filelist[[x]],envir=.GlobalEnv)))

此答案旨在作為Hadley答案的更有用的補充。

盡管OP特別希望每個文件都作為一個單獨的對象讀入R工作區,但是許多其他天真的落在這個問題上的人可能會認為這就是他們想要做的事情,實際上,最好是將文件讀為一個單獨的對象數據幀列表。

因此,記錄在下,您可能會這樣做。

#If the path is different than your working directory
# you'll need to set full.names = TRUE to get the full
# paths.
my_files <- list.files("path/to/files")

#Further arguments to read.csv can be passed in ...
all_csv <- lapply(my_files,read.csv,...)

#Set the name of each list element to its
# respective file name. Note full.names = FALSE to
# get only the file names, not the full path.
names(all_csv) <- gsub(".csv","",
                       list.files("path/to/files",full.names = FALSE),
                       fixed = TRUE)

現在,任何文件都可以由my_files[["filename"]]引用,這實際上並不比在工作區中只有單獨的filename變量很多,並且通常更方便。

從文件夾中讀取所有CSV文件並創建與文件名相同的目錄:

setwd("your path to folder where CSVs are")

filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))

for(i in filenames){
  assign(i, read.csv(paste(i, ".csv", sep="")))
}

從全局環境訪問列表元素的一種簡單方法是attach列表。 請注意,這實際上在搜索路徑上創建了一個新環境,並將列表中的元素復制到其中,因此,您可能需要在附加后刪除原始列表,以防止有兩個可能不同的副本在周圍徘徊。

簡化版本,假設您的 csv 文件位於工作目錄中:

listcsv <- list.files(pattern= "*.csv") #creates list from csv files
names <- substr(listcsv,1,nchar(listcsv)-4) #creates list of file names, no .csv
for (k in 1:length(listcsv)){
  assign(names[[k]] , read.csv(listcsv[k]))
}
#cycles through the names and assigns each relevant dataframe using read.csv

我想更新喬蘭給出的答案:

#If the path is different than your working directory
# you'll need to set full.names = TRUE to get the full
# paths.
my_files <- list.files(path="set your directory here", full.names=TRUE)
#full.names=TRUE is important to be added here

#Further arguments to read.csv can be passed in ...
all_csv <- lapply(my_files, read.csv)

#Set the name of each list element to its
# respective file name. Note full.names = FALSE to
# get only the file names, not the full path.
names(all_csv) <- gsub(".csv","",list.files("copy and paste your directory here",full.names = FALSE),fixed = TRUE)

#Now you can create a dataset based on each filename
df <- as.data.frame(all_csv$nameofyourfilename)

使用list.filesmap_dfr讀取許多 csv 文件

df <- list.files(data_folder, full.names = TRUE) %>%
    map_dfr(read_csv)

可重現的例子

首先將示例 csv 文件寫入臨時目錄。 它比我想象的要復雜。

library(dplyr)
library(purrr)
library(purrrlyr)
library(readr)
data_folder <- file.path(tempdir(), "iris")
dir.create(data_folder)
iris %>%
    # Keep the Species column in the output
    # Create a new column that will be used as the grouping variable
    mutate(species_group = Species) %>%
    group_by(species_group) %>%
    nest() %>%
    by_row(~write.csv(.$data,
                      file = file.path(data_folder, paste0(.$species_group, ".csv")),
                      row.names = FALSE))

將這些 csv 文件讀入一個數據幀。 注意 Species 列必須存在於 csv 文件中,否則我們會丟失該信息。

iris_csv <- list.files(data_folder, full.names = TRUE) %>%
    map_dfr(read_csv)
#copy all the files you want to read in R in your working directory
a <- dir()
#using lapply to remove the".csv" from the filename 
for(i in a){
list1 <- lapply(a, function(x) gsub(".csv","",x))
}
#Final step 
for(i in list1){
filepath <- file.path("../Data/original_data/..",paste(i,".csv",sep=""))
assign(i, read.csv(filepath))
}

暫無
暫無

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

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