R 在读取和合并多个文件时向表中添加文件名列
我在一个文件夹中有几个.csv文件,它们的列名相同 我想合并它们,并将每个文件的名称添加为第一列 我试过了R 在读取和合并多个文件时向表中添加文件名列,r,R,我在一个文件夹中有几个.csv文件,它们的列名相同 我想合并它们,并将每个文件的名称添加为第一列 我试过了 filenames <- list.files(getwd(), full.names = FALSE, pattern = ".csv", recursive = TRUE) sites <- str_extract(filenames, ".csv") # same length as filenames library(purr
filenames <- list.files(getwd(), full.names = FALSE, pattern = ".csv", recursive = TRUE)
sites <- str_extract(filenames, ".csv") # same length as filenames
library(purrr)
library(dplyr)
library(readr)
stopifnot(length(filenames)==length(sites)) # returns error if not the same length
ans <- map2(filenames, sites, ~read_csv(.x) %>% mutate(id = .y)) # .x is element in filenames, and .y is element in sites
通过此操作,文件将被合并,但第一列是数字而不是文件名
像
我也试过了,但是说CHROM列是双数字和双字符的
customized_read_csv <- function(file){
read_csv(file) %>%
mutate(fileName = file)
}
list.files(full.names = TRUE) %>% # list all the files
lapply(customized_read_csv) %>% # read them all in with our custom function
reduce(bind_rows) %>% # stack them all on top of each other
select(CHROM, fileName, N_VAF) %>% # select the correct columns
pivot_wider(names_from = fileName, values_from = N_VAF) # and switch from "long format" to "wide format"
Error: Can't combine `..1$CHROM` <character> and `..13$CHROM` <double>.
有什么帮助吗
编辑
我的档案看起来
最后的文件看起来
> head(ans)
# A tibble: 6 x 10
X1 CHROM POS REF ALT T_ALT_COUNT N_REF_COUNT N_ALT_COUNT id T_REF_COUNT
<dbl> <chr> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <chr> <dbl>
1 1 chrM 8620 C A 2161 607 1 LP200… NA
2 2 chr1 983023 C T 9 31 0 LP200… NA
3 3 chr1 1205584 T A 9 23 0 LP200… NA
4 4 chr1 1495120 T G 7 29 0 LP200… NA
5 5 chr1 1772044 C T 16 39 1 LP200… NA
6 6 chr1 2302194 G T 10 20 0 LP200… NA
>
我怎样才能避免这种情况呢?您可以使用sub获取文件名。在某些文件中,CHROM列似乎是以数字形式读取的,我们可以显式地将其转换为字符。尝试:
library(dplyr)
library(purrr)
sites <- sub('\\.csv$', '', basename(filenames))
ans <- map2_df(filenames, sites, ~read_csv(.x) %>%
mutate(CHROM = as.character(CHROM), id = .y))
用站点替换站点感谢您的工作,如何将列表转换为数据框?现在我有了带有文件名的列名id,但我不知道如何将这个大列表转换为数据框使用map2_df而不是map2。谢谢map2_df给出了这个错误:无法组合CHROM和CHROM。很抱歉,在我的新数据中@Ronak Shah,因为我在每个文件的第一列中都有一个空列,在最终的统一文件中,我有一个空栏,请看我编辑的帖子。你能把这个作为一个新问题问吗?延伸的问题可能会让未来的读者感到困惑。谢谢。我问了一个新问题,请看一看
> head(ans)
# A tibble: 6 x 10
X1 CHROM POS REF ALT T_ALT_COUNT N_REF_COUNT N_ALT_COUNT id T_REF_COUNT
<dbl> <chr> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <chr> <dbl>
1 1 chrM 8620 C A 2161 607 1 LP200… NA
2 2 chr1 983023 C T 9 31 0 LP200… NA
3 3 chr1 1205584 T A 9 23 0 LP200… NA
4 4 chr1 1495120 T G 7 29 0 LP200… NA
5 5 chr1 1772044 C T 16 39 1 LP200… NA
6 6 chr1 2302194 G T 10 20 0 LP200… NA
>
library(dplyr)
library(purrr)
sites <- sub('\\.csv$', '', basename(filenames))
ans <- map2_df(filenames, sites, ~read_csv(.x) %>%
mutate(CHROM = as.character(CHROM), id = .y))