[英]Combine some csv files into one - different number of columns
我已經加載了20個具有功能的csv文件:
tbl = list.files(pattern="*.csv")
for (i in 1:length(tbl)) assign(tbl[i], read.csv(tbl[i]))
要么
list_of_data = lapply(tbl, read.csv)
它看起來如何:
> head(tbl)
[1] "F1.csv" "F10_noS3.csv" "F11.csv" "F12.csv" "F12_noS7_S8.csv"
[6] "F13.csv"
我必須將所有這些文件合並為一個。 我們將其稱為主文件,但讓我們嘗試制作一個包含所有名稱的表。 在所有這些csv文件中都有一個名為“Accession”的列。 我想從所有這些csv文件中創建一個包含所有“名稱”的表。 當然,許多種質可以在不同的csv文件中重復。 我想保留所有與加入相對應的數據。
一些問題:
這是顯示這些數據的截圖: http : //imageshack.com/a/img811/7103/29hg.jpg
讓我告訴你它的外觀:
AT3G26450.1 <--
AT5G44520.2
AT4G24770.1
AT2G37220.2
AT3G02520.1
AT5G05270.1
AT1G32060.1
AT3G52380.1
AT2G43910.2
AT2G19760.1
AT3G26450.2 <--
<--
= 相同的樣本,不同的名稱。 應該被視為一個。 所以只需忽略點和數字。
有可能嗎?
我不能做一個dput(head)
因為它甚至是太大的數據集。
我試着使用這樣的代碼:
all_data = do.call(rbind, list_of_data)
Error in rbind(deparse.level, ...) :
The number of columns is not correct.
all_data$CleanedAccession = str_extract(all_data$Accession, "^[[:alnum:]]+")
all_data = subset(all_data, !duplicated(CleanedAccession))
我試着做了差不多兩個星期,我無法做到。 所以請幫助我。
您的問題似乎包含多個子問題。 我鼓勵你把它們分開。
您顯然需要的第一件事是將數據框與不同的列組合在一起。 您可以使用rbind.fill
從plyr
包:
library(plyr)
all_data = do.call(rbind.fill, list_of_data)
下面是一個使用一些tidyverse
函數和一個自定義函數的示例,該函數可以將多個缺少列的csv文件組合到一個數據框中:
library(tidyverse)
# specify the target directory
dir_path <- '~/test_dir/'
# specify the naming format of the files.
# in this case csv files that begin with 'test' and a single digit but it could be as just as simple as 'csv'
re_file <- '^test[0-9]\\.csv'
# create sample data with some missing columns
df_mtcars <- mtcars %>% rownames_to_column('car_name')
write.csv(df_mtcars %>% select(-am), paste0(dir_path, 'test1.csv'), row.names = FALSE)
write.csv(df_mtcars %>% select(-wt, -gear), paste0(dir_path, 'test2.csv'), row.names = FALSE)
write.csv(df_mtcars %>% select(-cyl), paste0(dir_path, 'test3.csv'), row.names = FALSE)
# custom function that takes the target directory and file name pattern as arguments
read_dir <- function(dir_path, file_name){
x <- read_csv(paste0(dir_path, file_name)) %>%
mutate(file_name = file_name) %>% # add the file name as a column
select(file_name, everything()) # reorder the columns so file name is first
return(x)
}
# read the files from the target directory that match the naming format and combine into one data frame
df_panel <-
list.files(dir_path, pattern = re_file) %>%
map_df(~ read_dir(dir_path, .))
# files with missing columns are filled with NAs.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.