在R中同时读取多个CSV文件并将其全部组合成一个数据帧 [英] Reading Many CSV Files at the Same Time in R and Combining All into one dataframe

查看:705
本文介绍了在R中同时读取多个CSV文件并将其全部组合成一个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有20个.CSV文件,它们都具有相同数量的行/列(1行和42列)。我想制作一个数据帧,并将每个CSV文件作为我的数据帧的一行,并将CSV文件的名称作为行名。是否可以这样做?



举例说明:

  A.csv 
10 21 32 45

B.csv
33 45 93 90

C.csv
12 93 Na 21

我正在寻找的结果数据框将是:

  A 10 21 32 45 
B 33 45 93 90
C 12 93 Na 21
/ pre>

解决方案

data.table rbindlist )和 dplyr bind_rows )具有这样的功能。我的首选解决方案是使用 readr :: read_csv dplyr :: bind_rows 一起执行此操作:

  library(readr)
库(dplyr)

bind_rows(
lapply b $ b list.files(
path / to / csv_files,
pattern =.csv,
full.names = TRUE
),
read_csv ,
header = FALSE,
na_strings = c(Na)



I have 20 .CSV files and all of them have equal number of row/col (1 row and 42 columns). I want to make a dataframe out of all them and have each CSV file as one row of my dataframe and have the name of the CSV file as my row name. Is it even possible to do this?

To illustrate this with an example:

A.csv
10 21 32 45

B.csv
33 45 93 90

C.csv
12 93 Na 21

Resulting dataframe I am looking for would be:

A 10 21 32 45
B 33 45 93 90
C 12 93 Na 21

解决方案

Both data.table (rbindlist) and dplyr (bind_rows) have functions to do this. My preferred solution would be to use readr::read_csv together with dplyr::bind_rows to do this:

library(readr)
library(dplyr)

bind_rows(
  lapply(
    list.files(
      "path/to/csv_files", 
      pattern = ".csv", 
      full.names = TRUE
    ), 
    read_csv, 
    header = FALSE, 
    na_strings = c("Na")
  )
)

这篇关于在R中同时读取多个CSV文件并将其全部组合成一个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆