Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R 3.0.3 rbind multiple csv files

Tags:

r

csv

rbind

R 3.0.3: I have 40 csv files all structured the same that I want to rbind into one file so I can calculate the mean of one column.

I searched:

  • this website
  • R in a Nutshell
  • R_Intro sources
  • ?rbind Help in RStudio

I cannot find the answer.

Any suggestions/pointers?

like image 620
user3551565 Avatar asked Apr 19 '14 11:04

user3551565


People also ask

Can R read multiple CSV files?

Using R Base read. R base function provides read. csv() to import a CSV file into DataFrame. You can also use to this to import multiple CSV files at a time in R.


2 Answers

Using the answer from here [Importing several files and indexing them ]

list files with .csv extension - this assumes that the only .csv files in your working directory are the ones you want to read

files  <- list.files(pattern = '\\.csv')

read files into a list - are there headers?

tables <- lapply(files, read.csv, header = TRUE)

rbind files

combined.df <- do.call(rbind , tables)

You can then find the mean - find which columns are numeric

s <- sapply(combined.df, is.numeric)

find the mean of numeric variables

colMeans(combined.df[s])
like image 173
user20650 Avatar answered Sep 20 '22 01:09

user20650


In more contemporary plyr approach:

files <- list.files(...)
data <- adply(files, 1, read.table)

(it's saturday afternoon: untested code, but the approach is fine)

like image 27
Paul Lemmens Avatar answered Sep 22 '22 01:09

Paul Lemmens