![](/img/trans.png)
[英]R Combine multiple .csv files and retain source csv file name in an additional column
[英]How to combine different .csv files to one complete file by adding the data of every file as an additional row using R?
我有幾個不同的文件夾,每個文件夾都包含一個.csv文件。 所有這些.csv文件都有一列,其中包含一項實驗條件的數據。 我想合並這些.csv文件,使每個文件的數據都添加為新列。
目前,它看起來像這樣:
C1.csv
102
106
152
196
223
486
553
C2.csv
296
299
843
1033
1996
但是,它希望有一個單個.csv文件,其中所有單獨的文件都復制到包含源文件名稱的新列中,例如:
C1 C2 ... Cn
102 296 ... ...
106 299 ...
152 843 ...
196 1033 ...
223 1996 ...
486 ...
553 ...
到目前為止,我的代碼如下:
myFiles = list.files(path = ".", recursive = TRUE, pattern = ".csv", full.names = TRUE)
data <- lapply(myFiles, read.table, sep="\t", header=FALSE)
Max <- max(sapply(data, length))
data <- lapply(data, function(x) c(x, rep(NA, Max - length(x))))
data <- do.call(cbind, data)
names(data) <- sub("^[^[:alnum:]]*([[:alnum:]]+)\\.csv$", "\\1", myFiles)
write.csv(data, "outfile.csv")
它產生了一個看起來像這樣的文檔,而不是將每個.csv文件的數據添加到新列中:
這是你想要的嗎?
請注意,我使用scan
讀取了文件。 由於文件只有一列,因此不需要像read.csv
這樣的復雜功能。
myFiles <- list.files(path = ".", pattern = "^C.*\\.csv", full.names = TRUE, recursive = TRUE)
data <- lapply(myFiles, scan)
Max <- max(sapply(data, length))
data <- lapply(data, function(x) c(x, rep(NA, Max - length(x))))
data <- do.call(cbind, data)
names(data) <- sub("^[^[:alnum:]]*([[:alnum:]]+)\\.csv$", "\\1", myFiles)
write.csv(data, "outfile.csv")
"outfile.csv"
的內容是
"","V1","V2"
"1",102,296
"2",106,299
"3",152,843
"4",196,1033
"5",223,1996
"6",486,NA
"7",553,NA
可以使用列表中的read.table
讀取所有文件。 使用dplyr::bind_rows
合並所有數據。 然后,使用reshape2::dcast
擴展具有每個文件數據列的寬格式數據。
# Get list of files in directory
fileList <- list.files(".", "*.csv", full.names = TRUE)
# Read file data. This will generate a list containing dataframes
listData <- lapply(fileList, read.table)
# Name list using name of files
names(listData) <- gsub(".csv","",basename(fileList))
library(tidyverse)
library(reshape2)
bind_rows(listData, .id = "FileName") %>%
group_by(FileName) %>%
mutate(rowNum = row_number()) %>%
dcast(rowNum~FileName, value.var = "V1") %>%
select(-rowNum) %>%
write.csv(file="Result.csv")
# Content of Result.csv
# "","C1","C2"
# "1",102,296
# "2",106,299
# "3",152,843
# "4",196,1033
# "5",223,1996
# "6",486,NA
# "7",553,NA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.